【问题标题】:C++ Do while loop condition not workingC ++ Do while循环条件不起作用
【发布时间】:2017-01-24 11:31:31
【问题描述】:
#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' 或 'n' 选项,它也不会停止循环。 即使我输入“Y”或“y”,它也不会询问我想要多少次尝试。 相反,它只是直接询问我想输入什么整数。 请尝试复制并编译代码以进一步了解问题所在。请帮忙。

P.S.:这是我顺便做的一个猜谜程序……

【问题讨论】:

  • 您是否尝试过使用调试器单步执行您的代码?
  • 当显示的代码中没有任何内容时,如果显示的代码响应“Y”、“y”、“N”或“n”,这将是一个非常好的技巧去做。你的问题是你的计算机只做你告诉它做的事情,而不是你想让它做的事情。
  • 实际上是 'Y' 或 'y' 而不是 "Y" 或 "y" 因为选择被声明为 char 所以 'Y' 或 'y' 等于字母 Y 或 y。跨度>

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


【解决方案1】:

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

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

【讨论】:

  • 即使您输入了 Y 或 y 作为选项,它也会结束程序。
  • 在初始尝试次数变为 0 后是否再次询问尝试了多少次?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 2022-12-12
  • 1970-01-01
  • 2016-09-23
  • 2018-06-23
相关资源
最近更新 更多