为什么我在角球比赛中没有得到3次尝试

  • 本文关键字:3次 c
  • 更新时间 :
  • 英文 :


我是一个初学者,我知道这可能是愚蠢的(是的,我有"正确的"代码(,但有人能向我解释为什么我的代码不能正常工作吗(尝试3次(

int main()
{
int guess;
int winner = 5;
int numbertries = 0;
int maxtries = 3;
while (guess != winner && numbertries > 3)
;
{
printf("guess a number: ");
scanf("%d", &guess);
numbertries++;
if (guess == winner)
{
printf("you win");
}
else
{
printf("you lose");
}
}
return 0;
}

首先,您应该使用do{}while();。这样,当while进行测试时,guess变量就会有一个值。其次,将其从numbertries > 3更改为numbertries < 3,这样它就可以计算您的猜测。第三,一旦创建了变量maxtries,就应该使用它,而不是3

int main()
{
int guess;
int winner = 5;
int numbertries = 0;
int maxtries = 3;
do
{
printf("guess a number: ");
scanf("%d", &guess);
numbertries++;
if (guess == winner)
{
printf("you win");
}
else
{
printf("you lose");
}
}while(guess != winner && numbertries < maxtries);
return 0;
}

主要问题是您没有启动while循环,而且条件也是错误的。我已经评论了程序中的一些错误,也提出了一些建议。然后我添加了相同的代码并修复了错误。

带注释的原始代码

int main()
{
int guess;
int winner = 5;
int numbertries = 0;
int maxtries = 3;

//The first error that I see is that you used a semicolon after the while declaration.
//This is only used in the do-while loops, but in this case, you shouldn't use it because
//this will skip all the while loop.
//The second error is that you'r trying to repeat it when numbertries is higher than 3, but
//in the begginning, numbertries is 0. The condition should be 'numbertries < 3', so you can
//start the loop. Also I recommend you to use the variable 'maxtries' instead of the number itself.
while(guess != winner && numbertries > 3 );
{
printf("guess a number: ");
//Here I recommend you to clear the input buffer, using the command fflush(stdin);, included in the <stdio.h> library
scanf("%d", &guess);
numbertries++; 

if(guess == winner)
//At the end of the messages, you should add a new line character ('n')
{    printf("you win");   }

else {printf("you lose");}
}
return 0;
}

有固定错误的新代码

#include <stdio.h>
int main()
{
int guess;
int winner = 5;
int numbertries = 0;
int maxtries = 3;
while(guess != winner && numbertries < maxtries )
{
printf("guess a number: ");
fflush(stdin);
scanf("%d", &guess);
numbertries++; 

if(guess == winner) { printf("you winn"); }  
else { printf("you losen"); }
}
return 0;
}

希望我能帮忙!祝你好运

最新更新