1.代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void title()
{
printf("*******************\n");
printf("欢迎来到猜数字游戏!\n");
printf("*******************\n");
}
void game()
{
srand(time(0));
int guess = 0;
// 生成1到100之间的随机数
int number = rand() % 100 + 1;
// 记录猜测次数
int time = 0;
while (1)
{
printf("请输入你猜测的数字(1-100):");
scanf_s("%d", &guess);
// 猜测次数
time++;
//猜数字
if (guess < number) {
printf("你猜的数字小了。\n");
}
else if (guess > number) {
printf("你猜的数字大了。\n");
}
else {
printf("恭喜你,猜对了!你用了 %d 次猜中了数字 %d。\n", time, number);
break;
}
}
}
2.运行结果
、
3.代码
srand(time(0));使用 srand() 函数根据当前时间生成随机数种子,确保每次运行时 rand() 函数生成的随机数序列不同。
number = rand() % 100 + 1;生成一个1到100之间的随机整数。
通过循环、条件判断和用户输入输出,实现了一个简单的猜数字游戏,让玩家通过输入不同的猜测来猜中程序生成的随机数。