而循环计数器不增加

时间:2017-10-13 20:49:33

标签: c++ while-loop

我设置一个count变量= 1,然后在循环内增加1。在循环中,计数确实递增(cout确认这一点),但似乎计数在循环的每次迭代时重置自身。因此,count始终为== 2,if语句将永远不会执行,因为count!= 3。如何递增计数而不是每次将其重置为1?

int main()
{
long numberOfPeople;
int  count = 1;

cout << "Enter the current population: ";
cin >> numberOfPeople;

while (numberOfPeople < 1)
{
    count++;
    cout << "count: " << count << "\n";
    cout << "Invalid Entry. Number must be greater than 1. Try again." << "\n" ;
    if (count > 3)
    {
        cout << "Too many invalid entries. Program terminated. ";
        return 0;
    }
    return main();
    } 
} 

1 个答案:

答案 0 :(得分:2)

问题在于:

return main();

这是通过再次调用main()重新启动程序。因此,不是使用递增的while变量返回count循环的开头,而是返回重置它的int count = 1;语句。递归调用main()实际上是C ++中未定义的行为,尽管在C中允许它,许多C ++编译器会以类似的方式编译它。

我不确定你为什么要在那里发表声明,只是摆脱它。

另一个问题是numberOfPeople在循环期间永远不会改变。你需要把:

cin >> numberOfPeople;

位于while循环的底部。

while (numberOfPeople < 1)
{
    count++;
    cout << "count: " << count << "\n";
    if (count > 3)
    {
        cout << "Too many invalid entries. Program terminated. ";
        return 0;
    }
    cout << "Invalid Entry. Number must be greater than 1. Try again." << "\n";
    cin >> numberOfPeople;
}