C ++ while while循环条件不起作用

时间:2017-01-24 11:31:31

标签: c++ if-statement nested-loops do-while nested-if

#include<iostream>
#include<ctime>
#include<cstdlib>

using namespace std;

int main(){
int gnumber, rnumber;
    char choice;
    int tries;

    do {
    cout << "Welcome to the Number Guessing Game!" << endl;
    cout << endl; // breakline
    cout << "How many tries: ";
    cin >> tries;
    cout << endl;

    while (tries > 0){

    srand(time(NULL));
    rnumber = rand() % 99;

    cout <<"Enter an integer greater than or equal to 0 and less than 100:";
    cin >> gnumber;
    system("cls");

    if (tries != 1){
        if (gnumber < 100 && gnumber >= 0){

            if (gnumber == rnumber){
            cout << "Congratulations! You've guessed the number." << endl;
            tries--;
            cout << "Remaining tries: " << tries << endl;   
            }

            else if (gnumber > rnumber){
                cout << "Your guess is higher than the number." << endl;
                tries--;
                cout << " Guess Again!" << endl;
                cout << "Remaining tries: " << tries << endl;
            }
            else{
                cout << "Your guess is lower than the number." << endl;
                tries--;
                cout << " Guess Again!" << endl;
                cout << "Remaining tries: " << tries << endl;
            }
        }
        else
        cout << "Must greater or equal to 0 and lesser than 100!" << endl;
    }
    else 
    {
        cout << "Game over!" <<" The number is: " << rnumber << endl;
        cout << "Play Again? (Y/N)" << endl;
        cin >> choice;
        system("cls");

    }

    }
    }while(choice == 'Y' || choice == 'y'); //  

    system("pause");
    return 0;
    }

即使我输入选择作为N&#39; N&#39;或者&#39; n&#39;它会停止循环。 即使我进入&#39; Y&#39;或者&#39; y&#39;,它没有问我想要多少尝试。 相反,它只是直接询问我想要输入的整数。 请尝试复制和编译代码以进一步了解问题所在。请帮忙。

P.S。:这是我正在制作的猜测程序......

1 个答案:

答案 0 :(得分:0)

内部循环中的错误,如果使用输入的值不是1,则不会递减tries,因此它会卡住:

    else 
    {
        cout << "Game over!" <<" The number is: " << rnumber << endl;
        cout << "Play Again? (Y/N)" << endl;
        cin >> choice;
        system("cls");
        tries--; // add this
    }