我有這個程序要求用戶猜測一個在1到20之間隨機生成的數字。最後,我要求用戶是否想要再次輸入1來輸入yes和一個0沒有。我知道應該使用while循環,但是當我選擇1再次運行時,它只會再次運行第一行代碼。此外,我必須說明用戶不輸入1或0,它應該要求用戶輸入有效的輸入,直到它是有效的1或0。我相信我有這個正確但我不確定。任何幫助將是偉大的!讓程序再次運行在C中
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;
}