所以在我的代码中,如果你低估或高估,你必须猜一个数字。如何让while循环循环回输入,以便输入另一个数字?
#include <stdio.h>
int main(int argc, const char * argv[])
{
int number = 45;
printf("Please insert a number");
scanf("%d", &number);
if (number == 45){
printf("good job! You got the number right.");
return 0;
}
else if (number < 45){
while (number < 45 || number > 45){
printf("Your number is too low");
return 1;
}
}
else if (number > 45){
printf("Your number is too high!");
return 1;
}
}
答案 0 :(得分:1)
只需在代码周围添加while (1)
,然后删除错误放置的代码:
#include <stdio.h>
int main(int argc, const char * argv[])
{
while (1) {
int number = 45;
printf("Please insert a number");
scanf("%d", &number);
if (number == 45){
printf("good job! You got the number right.");
return 0;
}
else if (number < 45){
printf("Your number is too low");
}
else{
printf("Your number is too high!");
}
}
}
return
正在关闭该计划。因此,当用户没有猜到您的号码时,您不想返回
while (1)
是循环,只有在return 0
启动时(当玩家赢了)时才会退出。
此外,您不需要上次else if
。将其替换为else
,因为这是唯一剩下的情况。
答案 1 :(得分:1)
用循环包裹你的代码:
int number = 45;
while (1) {
printf("Please insert a number");
if (scanf("%d", &number) != 1) {
printf("not valid number, try again");
continue;
}
if (number == 45){
printf("good job! You got the number right.");
return 0;
}
if (number < 45){
printf("Your number is too low");
continue;
}
if (number > 45){
printf("Your number is too high!");
continue;
}
}
请注意,您还应检查scanf
的返回值,以确定该号码是否已成功读取。