我有这个程序要求用户猜测在1到20之间随机生成的数字。最后,我问用户是否要再次输入1表示是,0表示否。我知道应该使用while循环,但是当我选择1再次运行时,它只会再次运行第一行代码。此外,我必须考虑用户没有输入1或0,它应该要求用户输入有效的输入,直到它是有效的1或0.我相信我有这个正确,但我不确定。任何帮助都会很棒!
int main(void)
{
int trys=0;
int guess;
int points=0;
int number;
int again=1;
int count=1;
srand(time(NULL));
printf("\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\n-*-*-*-*-*-*-*-*-*-*-*-*-*-Guess the Number*-*-*-*-*-*-*-*-*-*-*-*-\n");
while(again!=0)
{
number=rand()%20 + 1;
printf("Guess a number between 1 and 20: ");
scanf("%i", &guess);
trys=trys+1;
while (trys<3)
{
if (guess<1 || guess>20)
{
printf("Invalid input! Enter a value between 1 and 20: ");
scanf("%i", &guess);
}
else if(guess>number)
{
/*If the area is incorrect, the user will get this message*/
printf("Guess Lower: ");
scanf("%i", &guess);
trys=trys+1;
if (trys==3 && guess==number)
{
printf("\nGood Job! You earned a point.\n");
points=points+1;
printf("You have %i points!\n",points);
}
}
else if (guess<number)
{
printf("Guess Higher: ");
scanf("%i", &guess);
trys=trys+1;
if (trys==3 && guess==number)
{
printf("\nGood Job! You earned a point.\n");
points=points+1;
printf("You have %i points!\n",points);
}
}
else if(guess==number)
{
trys=3;
printf("\nGood job! You earned a point.\n");
points=points+1;
printf("You have %i points!\n",points);
}
}
if (trys==3 && guess!= number)
{
printf("\nSorry, the number was %i. Try again.\n",number);
printf("You have %i total points\n\n",points);
}
printf("Would you like to play again? (1 for yes, 0 for no) ");
scanf("%i", &again);
while(count==3)
{
if(again>1 || again<0)
{
printf("Invalid input! Enter a 1 for yes or a 0 for no: ");
scanf("%i", &again);
}
else if(again==1 || again==0)
{
count=3;
}
}
printf("\n\n\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n");
}
return 0;
}
答案 0 :(得分:0)
发布的代码:
1) is missing the three needed header files stdio.h stdlib.h and time.h
2) fails to reset the `tries` counter at the top of the outermost loop
检查错误是一个非常好的主意,因此每次调用scanf()之后都应检查返回值(而不是参数值),以确保操作成功。
即。如果用户只输入换行符或输入alpha值或输入控制字符,例如^ d?
,该怎么办?在'while'循环中检查有效的'重播'条目(0 ... 1)。如果用户继续输入换行符或6或'n'或......
,该怎么办?对于良好的程序流程,对于外环,建议:`do .... while(1 == again);
顺便说一句:为了避免长时间无法通过代码搜索比较==
意外写为=
的位置,请将文字放在左侧。然后编译器会发现问题。
关于这个循环:
而(计数== 3) { if(再次&gt; 1 ||再次&lt; 0) { printf(“输入无效!输入1表示是或0表示否:”); scanf(“%i”,&amp;再次); } 否则如果(再次== 1 ||再次== 0) { 计数= 3; } }
将count计算为3是一个坏主意,因为循环不会修改count的值,并且count将始终为1,因此永远不会输入此循环