温馨提示×

c语言猜数字1到100游戏怎么实现

小亿
189
2023-08-15 18:39:01
栏目: 编程语言

以下是一个实现C语言猜数字1到100游戏的示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int number, guess, attempts = 0;
// 生成随机数
srand(time(NULL));
number = rand() % 100 + 1;
printf("欢迎参加猜数字游戏!\n");
printf("猜一个介于1到100之间的数字。\n");
do {
printf("请输入你的猜测:");
scanf("%d", &guess);
attempts++;
if (guess > number) {
printf("猜大了!\n");
} else if (guess < number) {
printf("猜小了!\n");
} else {
printf("恭喜你,猜中了!\n");
printf("你猜了 %d 次。\n", attempts);
}
} while (guess != number);
return 0;
}

这个程序的基本思路是:生成一个1到100之间的随机数,然后循环接受用户的输入猜测,根据用户的猜测输出相应的提示,直到用户猜中为止。程序记录了用户猜测的次数,并在猜中时输出猜测次数。

0