c++ Do-while循环停止
C++ Do-while loop stopping
我得到了一个任务,我们让一个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;
}
相关文章:
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 如何使用 do while 循环确定最高值和最低值
- do while 循环中的 if 语句以 yes 或 no 结尾
- 使用 while 或 do while 退出循环
- 带有开关语句的 do-while 循环 -- 无穷循环错误
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- 为什么我的 Do-while 循环无法在C++中运行菜单
- 如果语句不会在 do - while 循环中运行
- 如何在c++中读取do-while循环中的空白
- 将嵌套的 for 循环更改为 do-while 循环
- 如何修复不会在退出选择时终止的 do-while 循环
- 为什么这个do-while循环每隔一个循环只写入数组?
- C++ do/while 循环和 if/else: 骰子游戏 -- 第 75 行错误:"Cout"之前的预期"While" -- 如何解决这个问题?
- 卡在链表中的无限 Do-while 循环中
- 试图调节我的 do-while 以停止在终端中退出程序.菜单不会根据需要循环使用当前语句
- 使用基本 do-while 循环求解泊松方程
- do-while循环不会退出C
- 如何在C++中使用带有"do while"循环的计数器?
- 无休止的 do while 循环C++代码