【发布时间】:2020-08-26 13:58:15
【问题描述】:
感谢您过来看看这个。这是由 Visual c++ 制作的。
我想用随机数和算术运算做一个随机问题。
它应该给我一个新的问题,直到我得到正确的答案,当我得到正确的答案时,它应该被停止并关闭。但是,即使我得到了正确的答案,它也不会让我摆脱循环,而是不断给我一个新问题。请查看我制作的以下代码。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int ans;
srand(time(0));
printf("Making a random problem. \n");
int x = rand() % 100;
int y = rand() % 100;
int op = rand() % 4;
while (1) {
switch (op)
{
case 0:
printf("%d + %d = ", x, y);
scanf("%d", &ans);
if (x + y == ans)
{
printf("correct.\n");
break;
}
else
printf("wrong.\n");
case 1:
printf("%d - %d = ", x, y);
scanf("%d", &ans);
if (x - y == ans)
{
printf("correct.\n");
break;
}
else
printf("wrong.\n");
case 2:
printf("%d * %d = ", x, y);
scanf("%d", &ans);
if (x * y == ans)
{
printf("correct.\n");
break;
}
else
printf("wrong.\n");
case 3:
printf("%d / %d = ", x, y);
scanf("%d", &ans);
if (x / y == ans)
{
printf("correct.\n");
break;
}
else
printf("wrong.\n");
}
break; //*1
}
return 0;
}
当我得到正确答案时,你能告诉我如何摆脱循环吗? 我认为底部的 *1 突破会让我逃脱,但它没有用。我会提前感谢它。
【问题讨论】:
-
您可以拨打
continue; -
break在switch之后/之外将在任何情况下离开您的while循环。如果您想防止这种情况发生,请使用continue结束所有情况(包括default:)以跳过此(当然,case 1除外)。 -
我将此类问题视为来自数据提供者的消息,即您将太多内容打包到一个函数中。如果将循环和开关移动到另一个函数中,您可以在想要退出循环时
return。 -
一个更易于维护的变体是使用最初设置为
false的标志(例如bool变量),检查while条件并仅设置为true如果你想离开循环。 -
注意:无论您使用什么学习材料,似乎都在教您 C,而不是 C++。两种语言之间有一些相当大的区别。
标签: c++ loops while-loop switch-statement escaping