[Solved] C++ : error with total+= in a while loop


I can see a couple of errors in your code.

First, as Pete Becker noted (and Lightness Races in Orbit refined), total isn’t initialized, so its value is indeterminate. It could even be an invalid representation of a floating point number (e.g. a NaN ) and it isn’t for sure a valid starting point for your calculation.

Rising the warning level of your compiler would have helped you to spot this error. For example, with the command line parameters -Wall -Wextra, that’s what clang++ ouputs:

... warning: variable 'total' is uninitialized when used here [-Wuninitialized]  
      total+=donation[values];  
      ^~~~~
prog.cc:7:17: note: initialize the variable 'total' to silence this warning  
{   double total;  
                ^  
                 = 0.0
1 warning generated.

So, to follow their suggestion, you can just declare it as:

double total = 0.0;

Or reset its value before the calculation.

Second, your input loop isn’t correct:

while (values < 10  &&  cin >> donation[values] )
{   
    ++values;            // <- Why is it here?
    if (values < 10)
    {
        cout << "Enter value no " << (values+1) <<" :";
        total += donation[values];    // <- Is this executed for the last (9) index? 
    }
}

You could rewrite it like this:

while ( values < 10 )
{
    cout << "Enter value no " << (values+1) <<" :";
    cin >> donation[values];
    if ( !cin ) // <- Input error, deal with it, somehow
        break; 
    total += donation[values];  
    ++values;
}

3

solved C++ : error with total+= in a while loop