Need help with my code!!!:(

Hi everyone, I'm stuck with some problems here with my code.
My quest is to create a function that takes an int vector as in-parameter and return the average of the numbers within the vector. Also the parameter
n should hold the number of elements within the vector.
I'm getting errors like "Expected primary expression before "int" and "Too few arguments to function "float Medel(int v[], int n).

#include <iostream>
#include <iomanip>

using namespace std;

float Medelv;

float Medel(int v[], int n)
{
Medelv = v[] / sizeof (v);
n = sizeof (v);
cout<<n<<endl;
return Medelv;
}

int main()
{
int vektor[10] = {1, 3, 5, 6, 7, 8, 22, 34, 55, 78};
Medel(vektor);
cout<<Medelv<<endl;
}

Would really apprectiate some help guys, this is my first attempt ever.
Regards
Your code should look more like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

float Medel(int v[], int n)
{
    // missing code
    // needs to be added here
}

int main()
{
    int vektor[10] = {1, 3, 5, 6, 7, 8, 22, 34, 55, 78};
    float average = Medel(vektor, 10);
    cout << average << endl;
}


Inside the function, declare a float variable to store the total.
Set the initial value to zero.
float total = 0;
Loop through the array v, from 0 to n-1
for (int i=0; i<n; ++i)
add each element to the total.
After the loop has ended, calculate the average, it is total / n.
return that value from the function at the end.
Alternatively you can use some of the algorithms that come with the standard library:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> vektor {1, 3, 5, 6, 7, 8, 22, 34, 55, 78};
    double Medelv = std::accumulate(vektor.begin(), vektor.end(),0) / double(vektor.size());
    std::cout << Medelv << '\t';
}

Last edited on
Thank you so much for the fast replies, code works great now:)
Hmm, nevermind. The code runs but i don't think it calculates right.

This is what i've done:

#include <iostream>

using namespace std;

float Medel(int v[], int n)
{
float total = 0;
for(int i=0; i<n; ++i)
total += v[10];
float average = total / n;
return average;
}

int main()
{
int vektor[10] = {1, 3, 5, 6, 7, 8, 22, 34, 55, 78};
float average = Medel(vektor, 10);
cout << average << endl;
}
This line looks wrong
 
    total += v[10];

Array subscripts start from zero. For an array with 10 elements, the valid elements are fromv[0] to v[9].


You should be using the integer i as the subscript instead of a fixed number 10 (which is accessing an out of bounds eleventh element).
Topic archived. No new replies allowed.