源码
主要组成——随机数的生成
1、引入头文件
#include <stdlib.h> //rand()和srand()
#include <time.h> //time()
2、游戏菜单
int menu() {
printf("----------------------------------\n");
printf("**********运行游戏扣:1 **********\n");
printf("**********退出游戏扣:0 **********\n");
printf("----------------------------------\n");
}
3、生成随机数
int game() {
int sto = rand() % 100 + 1;//生成随机数,其中rand()函数返回的是0-32767之间的数字故而此处取余+1可以得到0-100之间的数,因为余数最大为99
//printf("产生一个随机数:%d\n", sto);
while (1) {
int guess = 0;
printf("我的数字:");
scanf("%d", &guess);
if (guess < sto) {
printf("猜小了\n");
}
else if (guess > sto) {
printf("猜大了\n");
}
else {
printf("恭喜你猜对了\n");
break;
}
}
}
4、主函数
int main() {
srand((unsigned int)time(NULL));//srand()随机数rand()的起点数设置,srand内加入一个随机数为起点,此处选择时间戳(时间戳是一串随机数),time()函数,赋空值,且强制转换成srand、的数据类型“unsigned int”
//且注意srand()函数若同一时间多次设置起点,可能会造成重复生成相同随机数,故而此处放到main函数中每次游戏都设置不同的起点,进入main函数后设置好起点数,进入游戏再生成随机数
int input = 0;
do {
menu();
scanf("%d", &input);
switch (input) {
case 1:
game();
break;
case 0:
printf("游戏已退出\n");
break;
default:
printf("请输入1/0\n");
break;
}
} while (input);
}
实现原理
主要为随机数的生成
c语言中生成随机数的函数为rand(),需要引用的头文件为#include <stdlib.h>
使用rand()前提是加上srand(),需要引用的头文件为#include <stdlib.h>,此函数是设置随机数的起点值,是随机的,使得rand()的值也变为真正意义上的随机值
上文意思是在调用rand之前,使用srand函数为伪随机数生成器提供起点。
因为srand()可以传入整形变量,故而可以是100/200/300…但要使其一直发生变化,可以用到电脑中的时间戳,c语言中获取时间戳的函数是time(),引入的头文件是#include <time.h>,但要注意的是,srand()中的数据类型为unsigned int,故而需要强制转换(unsigned int)time(null),此处的time传入空值即可
总结
需要用到的头文件:#include <stdlib.h> #include <time.h>
需要用到的函数:rand()、srand()、time()
随机数生成:
srand((unsigned int)time(NULL));
int sto = rand();