average of an array is not working

What's wrong with this code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

    float cal[5], total;
    int i,prom;

    for(i=0;i<5;i++){
        cout << "cal " << i << " ";
        cin >> cal[i];
        prom +=cal[i];
    }
    total = prom / 5

    cout << "promedio " << prom;

    return 0;
}


I need to introduce 5 numbers, then get the average of those. The thing is that the result is always wrong, but i have this cpp compiler on my android phone and there the code works.

Any help is welcome. Thanks in advance

On line 10, use 5.0 instead of 5. You need at least one floating point type with division, or you will get integer division - it doesn't matter where the result goes, float or not.

Also, prom needs to be a floating point type - line 8 doesn't make sense.

Also, prefer double over float - the only time to use float is in cases where you need so many that memory is tight, which is rare.
Last edited on
like this?

1
2
3
4
5
6
7
8
9
10
11
12
 double calif[5], total, aver;
    int i;

    for(i=0;i<5;i++){
        cout << "cal " << i << ": ";
        cin >> calif[i];
        aver +=calif[i];
    }

    total = aver / 5.0;

    cout << "promedio " << total;


is not working either, i introduce 1,2,3,4,5...
(1+2+3+4+5)/5 must be 3.... and i get "1.4641e+264" as a result....
well.. i solved... it was just:

double calif[5], total=0, aver=0;

im a dumb >_>
Topic archived. No new replies allowed.