Arrays with functions

I am trying to complete this program, but i cant get it to work.

So i should create this function with the following head
"float medel(int v[], int n)"

so the function should take the total sum in the array in main and return the average number the array has.

So i know in my head how it should work, but i cant write it out... and now looking if someone can guide me in the right direction.


atm my main looks like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include "medel.h"
; using namespace std;

int main()
{
	int n = 5;
	float speed[] = { 30, 50, 75, 100, 110 };
	float speedsum = speed[0] + speed[1] + speed[2] + speed[3] + speed[4];
	float medel = speedsum;
	cout << medel << endl;



}





and my function looks like this
1
2
3
4
5
6
7
8
float medel(int speedsum, int n)
{
	float medel = speedsum / n;
	return medel;



}



I get the following error when i try to run it
Error C4335 Mac file format detected: please convert the source file to either DOS or UNIX format

What am i doing wrong?

Thanks for any help given :)
Last edited on
Apperently i should create a loop in the function that counts the amounts of elements in the array? How do i make the function count the amount of elements of an array?
Aren't you already sending in the amount of elements in the array?

float medel(int speedsum, int n)

isn't that the purpose of int n ?
Yes i am, but if i wanted the function to find that out for himself, how would i do that?
It's not possible.

If you want to do that, use a real container like std::vector - it has a .size() function, among other things.
Alright thank you. But how do i call the function to use it on the variabel speedsum?
I want the average out of speedsum, and i want the function to do that for me.
Last edited on
Your function already returns the average. Do you instead want it to also compute the sum?
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include "medel.h"
; using namespace std;

int main()
{
	int n = 5;
	float speed[] = { 30, 50, 75, 100, 110 };
	float speedsum = speed[0] + speed[1] + speed[2] + speed[3] + speed[4];
	float medel123 = speedsum;
	cout << medel123 << endl;
}


1
2
3
4
5
float medel123(int speedsum, int n)
{
	float medel = speedsum / n;
	return medel;
}



The only output i get is 365, so i havent figured it out how to call the function i think...
You need to call the function. Delete line 10 and replace line 11 with cout << medel123(speesum, n) << endl;
Ooooh i got it now, Thank you so much!
Topic archived. No new replies allowed.