我正在研究一個猜謎遊戲。環路因條件而終止,但條件是必要的?
問題是我必須將remainingguesses
設置爲0,這樣一個人可以使得猜測的數量減少1個。但是同時循環中設置的條件是基於remainingguesses
不是0。它是0循環終止並繼續。
我不知道如何解決這個問題,同時使循環中的條件正常工作。
這裏是有問題的循環:
printf("Type the number of guesses that player 2 gets and press return: \n");
scanf("%d",&guesses);
remainingguesses = 0;
while (remainingguesses != 0) {
printf("Player 2: Type your guess and press return (guesses remaining:%d):\n",remainingguesses);
scanf(" %d",&secretnumberguess);
remainingguesses = guesses - 1;
if (secretnumberguess > secretnumber) {
printf("Your guess was greater than the secret number.\n");
}
else if (secretnumberguess < secretnumber){
printf("Your guess was less than the secret number.\n");
}
else{
printf("Your guess was equal to the secret number. You win!\n");
}
}
if (remainingguesses == 0)
printf("Sorry you are out of guesses. You lose.\n");
如果需要,這裏是有問題的全碼:
#include <stdio.h>
int main()
{
int secretnumber;
int guesses;
int secretnumberguess;
int remainingguesses;
while (1) {
printf("Player 1: Type a number between 0 and 99 and press return:\n");
scanf(" %d",&secretnumber);
if (secretnumber > 99 || secretnumber < 0) {
printf("Secret number cannot be greater than 99 or below 0.\n");
continue;
}
break;
}
printf("Type the number of guesses that player 2 gets and press return: \n");
scanf("%d",&guesses);
remainingguesses = 0;
while (remainingguesses != 0) {
printf("Player 2: Type your guess and press return (guesses remaining:%d):\n",remainingguesses);
scanf(" %d",&secretnumberguess);
remainingguesses = guesses - 1;
if (secretnumberguess > secretnumber) {
printf("Your guess was greater than the secret number.\n");
}
else if (secretnumberguess < secretnumber){
printf("Your guess was less than the secret number.\n");
}
else{
printf("Your guess was equal to the secret number. You win!\n");
}
}
if (remainingguesses == 0)
printf("Sorry you are out of guesses. You lose.\n");
return 0;
你'remainingguesses =猜測 - 1;'但是你沒有在循環改變'guesses',所以剩下的沒有變化猜測的數目。你可能需要'剩下的猜測 - 或'或者同等的東西。事實上,我可能會做不同的事情。我可能會計算所採用的猜測次數:'int num_guesses; for(num_guesses = 0; num_guesses
這與['while while循環無法開始 - 忽略if語句和條件作爲結果]密切相關(https://stackoverflow.com/questions/43244415/while-loop-failing-to-begin-ignoring-if -statements和 - 條件 - 作爲一種結果);同一作者,同一個基本程序。 –
對不起,但你的意思是剩餘的猜測 - ;你的意思是用一些變量或從字面上減去它。 –