c++ Do-while循环停止

C++ Do-while loop stopping

本文关键字:循环 Do-while c++      更新时间:2023-10-16

我得到了一个任务,我们让一个cmd提示符显示并显示乘法的抽认卡游戏。输入正确答案后,系统会提示用户"再次输入?"Y/n,在第二个输入答案后,询问用户的提示不会出现,而是停留在"祝贺"信息上。当我编写代码为游戏随机生成两个数字时,就会发生这种情况。一个在while循环外,一个在while循环内。如果我为随机数留下第二个代码,它将运行良好,但只会再次显示相同的数字。我要问的是我如何修复它,这样它就不会在第二个答案输入后卡住?

示例代码如下:

#include <iostream>
using namespace std;
int main()
{
    int num1, num2, ans, guess, count = 0;
    char choice;
    num1 = rand() % 12 + 1;  
    num2 = rand() % 12 + 1;
    //first number generator.
    ans = num1 * num2;
    do
    {
        {
            cout << num1 << " X " << num2 << " = ";
            cin >> guess;
            cout << "Wow~! Congratulations~! ";
            count++;
            num1 = rand() % 12 + 1;
            num2 = rand() % 12 + 1;
            //second number generator.
        } while (guess != ans);

        cout << "nAgain? Y/N: ";
        cin >> choice;
    } while ((choice == 'y') || (choice == 'Y'));
    //after two turns the loop stops. Can't make a choice.
    cout << " Thanks for playing! Number of tries:" << count << endl;
    return 0;
}

我猜这个问题是因为你的循环并不完全像你想象的那样。

do
{

上面的代码已经启动了一个do循环。

    {

我怀疑你打算在这里开始另一个(嵌套的)do循环——但是你离开了do,所以它只是一个进入、执行和退出的块。在这种情况下,无用和无意义。

        cout << num1 << " X " << num2 << " = ";
        cin >> guess;
        cout << "Wow~! Congratulations~! ";
        count++;
        num1 = rand() % 12 + 1;
        num2 = rand() % 12 + 1;
        //second number generator.
    } while (guess != ans);

你已经格式化了这个,好像while正在关闭嵌套的do循环——但是因为你实际上没有创建一个嵌套的do循环,这只是一个空体的while循环。如果稍微重新格式化一下,它的含义会更明显:

    // second number generator
}
while (guess != ans)
    /* do nothing */
    ;

问题在这里:

do
{
    {
        cout << num1 << " X " << num2 << " = ";
        cin >> guess;

可以看到,第二个作用域没有do语句。因此,它只是一个代码块。

您可以通过为第二个代码块编写do语句来解决它。

因为do不存在于第二个括号中({),所以while被解释为while循环:

while (guess != ans);

while (guess != ans) {
}
因此,

将继续循环,直到guess不等于ans。但由于在循环中没有修改这两个变量中的任何一个,因此循环将继续迭代。


其他错误:注意程序仍然是不正确的,因为它会声称你已经回答了这个问题,而不管答案是什么。您可以通过如下方式实现来修复它:

int main()
{
    int num1, num2, ans, guess, count = 0;
    char choice;
    do {
       num1 = rand() % 12 + 1;
       num2 = rand() % 12 + 1;
       ans = num1 * num2;
       do {
            cout << num1 << " X " << num2 << " = ";
            cin >> guess;
            if(guess == ans) {
                cout << "Wow~! Congratulations~! ";
            } else {
                cout << "No, wrong!n";
            }
            count++;
        } while (guess != ans);

        cout << "nAgain? Y/N: ";
        cin >> choice;
    } while ((choice == 'y') || (choice == 'Y'));
    //after two turns the loop stops. Can't make a choice.
    cout << " Thanks for playing! Number of tries:" << count << endl;
    return 0;
}