【发布时间】:2018-03-14 02:32:19
【问题描述】:
我有一个 C 语言程序,用户运行它来玩“猜数字”游戏。它可以正确运行以启动,但在用户输入 2 个数字(1 个初始数字和 1 个重试数字)后,程序在它应该有有限的尝试次数时重复。
这是我的程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
//----Guess a Number Game.-----------------------------------------
// srand and rand needs the #include <stdlib.h> library
srand(time(NULL)); //seeding the guess a number game with the system time, so the guess a # game always starts at a different point.
int guess;
int correctnum;
correctnum = rand();
printf("Enter a number:");
scanf("%i",&guess);
if(guess>correctnum) // If aa is greater than bb AND aa is greater than cc.
{
printf("Please enter another number, lower this time!");
scanf("%i",&guess);
main();
}
else if (guess<correctnum)
{
printf("Please enter another number, higher this time!");
scanf("%i",&guess);
main();
}
else if (guess==correctnum)
{
printf("You are a WINNER!\n");
printf("You guessed the number right and it was %i!\n",correctnum);
}
int repeat;
printf("Would you like to play again? 1=Yes and 2=No.");
scanf("%i",&repeat);
if(repeat==1)
{
main();
}
if(repeat==2)
{
printf("Hope you had a good time playing the game! See you soon!\n");
return 0;
}
}
【问题讨论】:
-
不要递归调用
main,使用循环。 -
至于你的问题,你应该运行多少“迭代”没有任何限制。
-
你在调用
main()之前使用scanf()并在函数顶部重复使用它 -
每次再次调用 main 时,都会重新设置 rng。
-
@Someprogrammerdude 有没有什么方法可以重写我的程序的一部分,这样就不需要循环了,它只使用 if 语句?
标签: c function if-statement