C ++:在while循环中使用total + =的错误

时间:2018-04-12 18:37:56

标签: c++ arrays if-statement while-loop increment

我是编程新手,目前正在阅读“C ++ Primer Plus”一书。这是我为某一章所做的整个练习。这段代码的结果并非我认为的那样(我希望只会将捐款[1]的价值添加到捐款[9])。

#include <iostream>


using namespace std;

int main()
{   double total;
    int bigger=0;
        int values=0;
    double donation[10];

    cout<<"Enter 10 donation values(numbers only). ";
    cout<<"Enter first value: ";

    while (values<10 && cin>>donation[values] )
    {   ++values;
        if (values<10)
        {
        cout<<"Enter value no " <<(values+1)<<" :";
        total+=donation[values];
    }
    }
    double average=total/10;

    for ( values=0; values<10; values++)
    {
    if (donation[values]> average)
    {
        bigger++;
    }

    }
    cout<<"The average of the numbers is: "<<average<<endl;
    cout<< bigger <<" numbers larger than average. \n";
    cout<<"Bye";



    return 0;
}

以下是我运行程序时获得的示例:

Enter 10 donation values(numbers only). Enter first value: 1
Enter value no 2 :2
Enter value no 3 :3
Enter value no 4 :4
Enter value no 5 :5
Enter value no 6 :6
Enter value no 7 :7
Enter value no 8 :8
Enter value no 9 :9
Enter value no 10 :10
The average of the numbers is: 6.15278e-311
10 numbers larger than average. 
Bye 

1 个答案:

答案 0 :(得分:1)

我可以在你的代码中看到一些错误。

首先,当Pete Becker注明(和Lightness Races in Orbit已完成)时,total未初始化,因此其值不确定。它甚至可能是浮点数的无效表示(例如NaN),并且它不是确定计算的有效起点。

提高编译器的警告级别可以帮助您发现此错误。例如,使用命令行参数-Wall -Wextra,那就是clang ++输出的内容:

... 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.

因此,要遵循他们的建议,您可以将其声明为:

double total = 0.0;

或在计算前重置其值。

其次,您的输入循环不正确:

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? 
    }
}

你可以像这样重写它:

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;
}