Well, I was hoping you would modify the function, rather than main().
But still, your latest example doesn't work because of two problems.
line 12
sum is type
int
10 is type
int
calculation is done using integer division, which means the decimal part of the result is lost.
Second problem, also line 12
result is assigned to variable average which is type
int
That means even if floating-point division was done, the result would still be truncated to an integer, losing the decimal part.
Also, there's no need to declare the variable
average
at the start, wait until you are ready to assign a proper value to it.
Here I used a constant named
size
instead of the literal 10. This makes the code easier to maintain, if the array size needed to change, you'd only have to change one place instead of three.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
using namespace std;
int main()
{
const int size = 10;
int array[size] = {1,2,3,4,5,6,7,8,9,10};
float sum = 0;
for (int i = 0; i < size; ++i)
sum += array[i];
float average = sum/size;
cout << "Average:" << average;
}
|