我需要幫助完成我的程序。我似乎無法得到最後一步,當用戶輸入'y'
來玩另一個遊戲時,它應該重新開始。如果用戶輸入'n'
那麼它應該結束。預先感謝您的任何幫助。以下是我到目前爲止的代碼。C編程猜測遊戲
問題出在這裏:
編寫一個C程序,與用戶一起玩猜數字遊戲。
下面是示例運行:
OK, I am thinking of a number. Try to guess it.
Your guess? 50
Too high!
Your guess? 250
Illegal guess. Your guess must be between 1 and 200.
Try again. Your guess? 30
**** CORRECT ****
Want to play again? y
Ok, I am thinking of a number. Try to guess it.
Your guess? 58
**** CORRECT ***
Want to play again? n
Goodbye, It was fun. Play again soon.
代碼:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i, number, currentGuess, MAX_GUESS = 5;
int answer = 'n';
time_t t;
srand((unsigned) time(&t));
number = rand() % 200 + 1;
printf("Welcome to the game of Guess It! \nI will choose a number between 1 and 200. \nYou will try to guess that number.");
printf("If you guess wrong, I will tell you if you guessed too high or too low. \nYou have 5 tries to get the number. \n");
printf("\nOK, I am thinking of a number. Try to guess it. \n");
for (i = 0; i < MAX_GUESS; i++) {
printf("\nYour guess?");
scanf("%i", ¤tGuess);
if (currentGuess > 200) {
printf("Illegal guess. Your guess must be between 1 and 200.\n");
printf("Try again.\n ");
}
else if (currentGuess > number) {
printf("Too high!\n");
}
else if (currentGuess < number) {
printf("Too low!\n");
}
else {
printf("****CORRECT****\n");
return 0;
}
}
printf("Sorry you have entered the maximum number of tries. \n");
printf("Want to play again? \n");
scanf("%i", &answer);
if(answer == 'n') {
printf("Goodbye, it was fun. Play again soon.\n");
return 0;
}
else if (answer != 'n') {
printf("Ok, I am thinking of a number. Try to guess it.\n");
}
}
將您的代碼導出到其他方法。 int game(){....}和main()只是調用game()。然後當你想讓用戶重新啓動時再次調用game() – Pentarex
你應該看看https://stackoverflow.com/questions/44742209/im-trying-to-code-a-number-guessing-game。看來你們都試圖解決類似的編碼問題。 –
然後看看'man scanf'並考慮'scanf(「%i」,&answer);'和if(answer =='n')'。具體是什麼問題可能是。當你輸入'n'作爲答案時,'scanf'認爲'n'是什麼? –