我剛剛開始學習C編程和練習,我發現這個任務。這是一個猜數字的遊戲,電腦猜測我想要的數字。首先,我必須考慮一個數字。然後我必須掃描數字的範圍。然後計算機產生一個範圍內的數字,並問我是否正確。基於計算機的答案,我必須回答L,如果它太低,H如果它太高,G如果它是正確的。如果它是正確的,它會將其輸出並嘗試嘗試。如果輸入任何其他字符,則打印出我輸入了錯誤的答案。C數字猜測遊戲
這就是我到目前爲止。它不會給我任何錯誤,但是當我輸入L,H或G時,它會打印出我輸入錯誤的答案。
在此先感謝您的幫助。
#include<stdio.h>
#include<stdlib.h>
void main(){
int randomNo = 0;
int input = 0;
int counter = 0;
int min = 0;
int max = 0;
char answer = ' ';
char low = 'L';
char high = 'H';
char good = 'G';
printf("Enter min and max: ");
scanf_s("%d %d", &min, &max);
do{
randomNo = min + rand() % (max - min) + 1;
printf("Is it %d?\n", randomNo);
printf("Enter your answer:");
scanf_s("%s", &answer);
if (answer == low){
printf("Number guessed is low\n");
min = randomNo;
counter++;
}
else if (answer == high){
printf("Number guessed is high\n");
max = randomNo;
counter++;
}
else{
printf("You entered the wrong answer!\nYour answer should be L - too low H - too high G - goed\n");
}
} while (answer != good);
printf("Your answer is correct!\nYou guessed it in %d times!\n", counter);
}
您的'if'語句也需要處理'answer == good',否則當您輸入'G'時會輸出錯誤的答案。你可以簡單地把最後一個'else'改成'else if(answer!= good)'。 – 2014-09-30 09:29:48
'void main()'應該是'int main(void)'。 – mch 2014-09-30 09:40:43
你使用'scanf_s'而不是'scanf'(或'fgets' /'getchar'等)的原因是什麼?它不太便於攜帶,沒有任何優勢。如果你要使用它(因爲它是你需要的或者類似的任務):你使用哪個版本 - 來自Microsoft的CRT版本還是來自C11的附件K的標準版本? – mafso 2014-09-30 13:53:57