C ++只有2次循环迭代

时间:2015-02-07 17:55:24

标签: c++

我在大学读书,我们开始用C ++编程。我有一些关于Java的基本概念(变量,循环和更容易的东西),我尝试用Microsoft Visual Studio自己练习,但是我遇到了问题,这是我的代码,是一个试图猜测你的数字的程序正在考虑。

void main(){
srand(time(NULL));
int number=1+rand()%100;
int highLow;
bool a;
a = true;
cout << "Think a number between 1 and 100 and I will guess it" << endl;
system("PAUSE");
cout << "\nIs it ";
cout << number;
cout << "?" << endl;
cout << "If the number is lower press 1, higher 2 and correct 3" << endl;
cin >> highLow;
while (a)
{
    if (highLow == 1)
    {
        number = 1 + rand() % number;
        cout << "\nIs it ";
        cout << number;
        cout << "?" << endl;
        cin >> highLow;
    }
    else if (highLow == 2)
    {
        number = rand() % (100 - number+1)+number;
        cout << "\nIs it ";
        cout << number;
        cout << "?" << endl;
        cin >> highLow;
    }
    else if (highLow == 3)
        cout << "I win this time" << endl;
        a = false;}
}   

问题是它应该根据需要多次询问用户来猜测数字,但它只会做2次,然后停止。你能帮帮我吗?

1 个答案:

答案 0 :(得分:1)

如果您只是正确地缩进了代码......

最后a = false;语句无论执行什么都会执行,因为它超出了最后else if语句的范围。基本上,这个:

else if (highLow == 3)
    cout << "I win this time" << endl;
    a = false;

表示以下内容:

else if (highLow == 3) {
    cout << "I win this time" << endl;
}

a = false;

您需要在适当的位置添加一些花括号。