gpt4 book ai didi

C scanf() 问题?

转载 作者:太空狗 更新时间:2023-10-29 15:32:14 25 4
gpt4 key购买 nike

在这个简单的猜数字游戏中,scanf() 在 main 中第二次不工作。如果有人能解释为什么不起作用以及如何解决它,我将不胜感激。关于如何清理此代码的任何提示?谢谢!

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int guessed = 0;
int guesses = 0;
int total_guesses = 0;
int range_top = 1;
int generate_random_number()
{
srand(time(NULL));
return (rand() % range_top);
}
void take_guess(int num)
{
int guess;
printf("what is your guess: ");
scanf("%i",&guess);
if(guess == num)
{
guessed = 1;
}
else if(guess>num)
{
printf("Your guess was too high,\n");
}
else
{
printf("Your guess was too low.\n");
}

}
int main(void)
{
printf("This is a game in C\n");
printf("Would you like to play? (y/n): ");
char play;
scanf("%c",&play);
while(play == 'y')
{
printf("I am thinking of a number between 0 and %i\n",range_top);
int num = generate_random_number();
while(guessed ==0)
{
take_guess(num);
guesses++;
}
printf("It took you ");
printf("%i",guesses);
printf(" guesses to win.\n");
printf("Would you like to play again? (y/n): ");
scanf("%c",&play);
guessed = 0;
guesses = 0;
total_guesses+=guesses;

}
printf("goodbye!");
}

最佳答案

这是一个典型的新手错误。

scanf("%c",&play);

读取take_guess中的数字后,将读取留在输入流中的换行符。

使用

scanf(" %c",&play);

相反。

当您在格式说明符中的 %c 之前有一个空白字符时,该函数将从输入流中读取第一个非空白字符。否则,它将从输入流中读取第一个可用字符。

关于C scanf() 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32236684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com