Average

Why the average is not working in here?


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
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
          const int age=6;
          int a[age];
          float average;
          
    for (int count=0; count<age; count++)
    {
        cout <<"ENTER AGE "<< count<<" : ";
        cin>>a[age];
        }
    int sum=0;
    for (int count=0; count<age; count++)
    {
        sum+=a[age];
        }
        average = (sum / 6);
    cout<<"The average is : "<< average <<endl;
    
    system("pause");
    return 0;
}
1
2
3
int sum=0;
/*...*/
sum / 6 // <- Integer division here 

Change this line to: average = (sum / 6.0);
You're doing integer division at line 20.
Both sum and 6 are integers.
The integer division is done before being assigned to the float.
Is the problem not that hes adding everything to position 6 in the array ?
Surely the code should be
1
2
3
4
5

    for (int count=0; count<age; count++)
    {
        sum+= a[count];
    }

if it were
 
sum+= a[age];

Age = 6
Therefore everything is added to postion 6 ?

edit: it would also be the same for

1
2
3
4
5
   for (int count=0; count<age; count++)
    {
        cout <<"ENTER AGE "<< count<<" : ";
        cin>>a[age];// should be cin >> a[count];
        }
Last edited on
@jidder

Good catch. You're correct.

age is certainly a poor choice of a name for an array limit.
Something like MAX_AGES would certainly have conveyed the meaning more clearly.

In both loops the OP should have been referring to a[count]

Thanks all of u :)
Topic archived. No new replies allowed.