I think you've done what the teacher meant, mostly :-)
In line 7 you've created an array of 10 integers, which means you now have 10 integers that you can manage as group, using a single label (n).
The elements of your array, i.e. your 10 integers are n[0], n[1],...[n[8], n[9]
In line 13 you are getting input of 10 integers from the user and storing them in these elements one at a time, and computing the average as you go along - actually, since you're computing the average on the fly, you don't need that array at all.
I think what the teacher really meant was for you to do this as a function, like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
using namespace std;
float medel(int v[], int n)
{
float res = 0.0;
for(int i = 0;i < n;i++){
cin >> v[i];
res +=((float)v[i]/n);
}
return res;
}
int main()
{
const int num = 10;
int n[num] = {0};
cout << "Welcome to the program. Enter 10 positive numbers: ";
cout << "The average of ten numbers entered is: " << medel(n, num) << endl;
return 0;
}
|
Consider using a
vector instead of array
Consider using
double instead of float
Consider using more descriptive variable names
Consider not using magic numbers like "10", prefer a symbolic name instead
Of course there are better ways of doing this, but I appreciate you're learning from a teacher and you have to get a good grade, which sometimes means doing things the teacher's way or else.
http://www.cplusplus.com/doc/tutorial/arrays/
http://www.cplusplus.com/doc/tutorial/functions/
Perhaps a little better:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
#include <vector>
using namespace std;
double medel(const vector<int> &numbers)
{
double res = 0.0;
for (int num : numbers)
res += (double) num / numbers.size();
return res;
}
int main()
{
cout << "Welcome to the program. Enter 10 positive numbers: ";
constexpr int nums = 10;
vector<int> numbers;
for(int i = 0;i < nums;i++){
int x;
cin >> x;
numbers.push_back(x);
}
cout << "The average of ten numbers entered is: " << medel(numbers) << endl;
return 0;
}
|