【发布时间】:2015-09-19 08:26:49
【问题描述】:
我得到了一个任务,我们让一个 cmd 提示符出现并显示一个用于乘法的抽认卡游戏。输入正确答案后,会出现提示并要求用户选择“Again?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;
}
【问题讨论】:
-
您缺少用于
while (guess != ans)循环的do动词。