编写一个猜数游戏,用C语言编译
时间: 2024-05-02 16:22:22 浏览: 10
好的,我可以为您提供一个简单的代码来实现猜数游戏。请用您的文本编辑器打开一个新的C文件,并将以下代码粘贴到该文件中:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int number, guess, nguesses = 1;
srand(time(0));
number = rand() % 100 + 1; //生成1到100之间的随机数
// printf("The number is %d\n", number); (测试用语句)
do
{
printf("Guess the number between 1 and 100\n");
scanf("%d", &guess);
if (guess > number)
{
printf("Lower number please\n");
}
else if (guess < number)
{
printf("Higher number please\n");
}
else
{
printf("Congratulations! You guessed it in %d attempts\n", nguesses);
}
nguesses++;
} while (guess != number);
return 0;
}
```
保存该文件并编译它。现在您可以运行程序,玩猜数游戏了。程序将生成一个1到100之间的随机数,您需要猜测该数字是多少。每猜一次,程序会告诉您是猜高了还是猜低了,直到您猜对为止。游戏结束后,程序将告诉您您猜测的次数。祝您好运!