gpt4 book ai didi

C++ Do-while循环停止

转载 作者:搜寻专家 更新时间:2023-10-31 00:11:47 24 4
gpt4 key购买 nike

我接到了一项任务,我们要显示一个 cmd 提示符并显示一个用于乘法的抽认卡游戏。输入正确答案后,会出现一个提示,要求用户选择“再次?是/否”。在第二次输入后回答询问用户的提示没有出现并且它停留在“祝贺”消息上。当我编写代码为游戏随机生成两个数字时,就会发生这种情况。一个在 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,所以它只是一个被输入、执行的 block ,并退出。在这种情况下毫无用处和意义。

        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 */
;

关于C++ Do-while循环停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32662789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com