I don't get it!!

Everything seems perfectly normal to me, but it doesn't work...
I'm making a prog that stores the numbers you enter and then - when you enter a negative value - calculates the average.

but when I let it play, it gives some totally wrong output

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
28
29
30
31
32
33
34
35
#include <iostream>

using namespace std;

int getal[128];
int i;
int a = 0;
int b;
double c;

int main ()
{
    cout<<"Dit programma telt alle getallen op en berekent dan het gemiddelde.\nOm het te stoppen, geef een negatief getal in.\n";
    while (true) {
    cin >> i;

    if (i>0)
    {
        getal[a] = i;
        b += getal[a];
        a++;
    }
    else
    {
        c = (b/a);
        cout<<"Average is "<<c<<".";
    }

    }




    return 0;
}
Last edited on
Why don't you just replay the program in your head step by step? Then you'll quickly see why it doesn't work.
Instead of accumulating a sum in b, you're always overwriting it with the last entered value.
I tried but I didn't see it...
what do you I'm overwriting?
Oh wait I see it, what a dull mistake...It has to be += instead of =.
But now it doesn't give a float/double but an int...
Yeah, when you divide two integers, the result is also an integer.
You will have to cast at least one of the values to a double.
It fixed it !

Thanks a lot Athar
Topic archived. No new replies allowed.