我有一個(gè)用于猜數(shù)字游戲的C程序,但當(dāng)我運(yùn)行這段代碼時(shí),它會(huì)進(jìn)入無(wú)限循環(huán),我認(rèn)為這是因?yàn)榈?1行中的scanf()!我該怎么解決這個(gè)問(wèn)題?
#include <stdlib.h>
#include <time.h>
int main(){
int number, guess, nguesses = 1;
char name;
srand(time(0));
number = rand()%100 + 1; // Generates a random number between 1 and 100
// Keeps running the loop until the number is guessed
printf("------| Welcome to Guess the number game |-------\n");
printf("Enter your name: ");
scanf("%c", name); ---> Causing infinite loop
do
{
printf("\nGuess the number between 1 to 100\n");
scanf("%d", &guess);
if(guess>number)
printf("Lower number please!\n");
else if(guess<number)
{
printf("Higher nummber please!\n");
}
else
{
printf("Congratulations you have correctly guessed the number!\nAttempts taken: %d\n", nguesses);
}
nguesses++;
}
while (guess!=number);
return 0;
}
name
時(shí),您為char
簽名,但名稱并不是只有一個(gè)字符。所以它必須是一個(gè)array
,當(dāng)你掃描時(shí),你使用%s
而不是%c
。(%c
表示字符,%s
表示char數(shù)組{您可以像string})。我嘗試了?在這里寫(xiě)的東西,很喜歡你的游戲。