我创建了一个简单的猜谜游戏程序。我的问题是,一旦用户输入错误的数字,我不确定如何将程序循环回程序的开头。我希望程序继续向用户询问一个数字,直到他做对了。有人能帮助我吗?
#include <stdio.h>
int main (void) {
int value = 58;
int guess;
printf("Please enter a value: ");
scanf("%i", &guess);
if (guess == value) {
printf("Congratulations, you guessed the right value");
}
else if (guess > value) {
printf("That value is too high. Please guess again: ");
scanf("%i", &guess);
}
else if (guess < value) {
printf("That value is too low. Please guess again: ");
scanf("%i", &guess);
}
return 0;
}
答案 0 :(得分:5)
这看起来像while
循环和break
语句的好地方。您可以像这样使用while
循环无限循环:
while (true) {
/* ... /*
}
然后,一旦某个条件成立并且您想要停止循环,您可以使用break
语句退出循环:
while (true) {
/* ... */
if (condition) break;
/* ... */
}
这样,当用户猜对时,您可以break
退出循环。
或者,您可以使用do ... while
循环,其条件检查循环是否应退出:
bool isDone = false;
do {
/* ... */
if (condition) isDone = true;
/* ... */
} while (!isDone);
希望这有帮助!
答案 1 :(得分:1)
C语法中有许多循环结构。他们是:
for()
while()
do/while()
这些中的任何一个都应该很容易查找您正在使用的任何参考材料,并且可以用来解决这个问题。
答案 2 :(得分:1)
试试这个:
printf("Please enter a value: ");
do {
scanf("%i", &guess);
if (guess == value) {
printf("Congratulations, you guessed the right value");
}
else if (guess > value) {
printf("That value is too high. Please guess again: ");
}
else if (guess < value) {
printf("That value is too low. Please guess again: ");
} while (guess != value);
答案 3 :(得分:0)
使用do { /*your code*/ } while(condition);
do {
/*your code*/
char wannaPlayAgain;
wannaPlayAgain = getchar();
} while(wannaPlayAgain=='y');
当然你应该修复它以防人们输入Y而不是y,但关键是你需要将你的程序包装在do while循环中(它将至少执行一次)或while循环(获取初始值)在您输入条件之前,具有初始启动条件。
答案 4 :(得分:0)
您的预期计划
#include <stdio.h>
void main (void) {
int value = 58;
int guess;
do
{
printf("please enter a value : ");
scanf("%i", &guess);
if(guess > value)
printf("this value is too big, ");
else if(guess < value)
printf("this value is too small, ");
}while(guess != value);
printf("Congradulation You Guessed The Right Number. \n");
}