在实际编程中,我们经常需要生成随机数。因此rand()与srand()出现了,本文详解随机数相关内容
一、rand()函数相关
- 函数头文件:stdlib.h
- 函数定义:int rand(void)
- 函数功能:产生一个随机数
- 返回值:返回0至RAND_MAX之间的随机整数值
- 下面我们来进行编写,看下结果
#include <stdio.h>
#include <stdlib.h>
int main(){
int a = rand();
printf("%d\n",a);
return 0;
}
- 当我们多次运行上面程序后发现,每次生成的数字都是一样的!所以我们来探索下rand()函数的本质:
二、rand()函数的本质——产生一个种子(一个随机数)
- 实际上,rand() 函数产生的随机数是伪随机数,是根据一个数值按照某个公式推算出来的,这个数值我们称之为“种子”
- 当我们定义了一个rand()函数,产生的虽然是随机数,但这个随机数在开始就已经产生了且不在变化
- 也可以说,程序运行时最开始时产生随机数,但后续就相当于一个固定值
- 既然只能产生一个种子(随机数),那么怎么样才能重新播种(产生新随机数)呢?
三、srand()函数——进行重新播种
- 函数头文件:stdlib.h
- 函数定义:void srand(unsinged int seed)
- 函数功能:设置随机数种子
- 函数说明:通常可以用getpid()(获取当前进程的进程识别码)或者time(NULL)(获取当前系统的时间信息)来充当种子,保持每次运行时的种子是不一样的
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int a;
srand(time(NULL));
a = rand();
printf("%d\n", a);
return 0;
}
- 多次运行后,发现每次运行结果不同,随机数产生成功!
四、生成一定范围内的随机数
- 在实际开发中,我们往往需要一定范围内的随机数,过大或者过小都不符合要求,那么,如何产生一定范围的随机数呢?我们可以利用取余的方法:
int a = rand() % 10; //产生0~9的随机数,注意10会被整除
int a = rand() % 9+1; //产生1-9的随机数
五、连续生成随机数
- 利用for循环 来试一下
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int a, i;
for (i = 0; i < 10; i++) {
srand((unsigned)time(NULL));
a = rand();
printf("%d ", a);
}
return 0;
}
运行结果.png
- 为什么每次运行结果都相同呢?因为某一小段时间的种子是一样的,利用for循环运行时间很短暂,time()函数只能精确到秒,但for太快,导致种子一样,那么随机数也就一样了
- 利用unsigned int seed = time(NULL); 定义一个时间种子seed,并在循环中每次将seed进行加减变化,srand(seed+=300)这样就表示播种时间不同了。我们将其写入程序:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
unsigned int seed = time(NULL);
int a, i;
for (i = 0; i < 10; i++) {
seed+=300; //让播种时间不同
srand(seed);
a = rand();
printf("%d ", a);
}
return 0;
}
修改后运行结果.png
- 我们可以看到每次循环的结果不同,问题得到解决!
六、for循环与随机数生成函数——记数字
小游戏:最强大脑
1 2 3 4
2s后消失
输入:刚才产生的数字 1 2 3 4
输入正确后,产生多一位元素的 随机数集合 重复游戏
- 导入头文件
#include <stdio.h>
#include <windows.h> //利用 system("cls") 当数字展示一定时间后进行清屏
#include <stdlib.h>
#include <time.h> //srand(time(NULL)) time 导入头文件 <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main(){
int count = 3; //记录每次生成多少个随机数
while(1)
{
unsigned int seed = time(NULL); //1000
count++; //每次多增加一个数字
//设置随机数的种子
srand(seed);
for(int i = 0; i < count; i++){
//生成一个随机数
int temp2 = rand() % 9 + 1;
printf("%d ",temp2);
}
printf("\n");
// 延时2s
Sleep(2000);
//for(int i = 0; i < 10000000000/15*2; i++);
//刷新屏幕
system("cls");
int temp;
printf("请输入:");
//重新设种子和之前生成时的种子一样
srand(seed);
//接收用户输入 一个一个接收
for(int i = 0; i < count; i++)
{
scanf("%d", &temp);
//获取对应的生成的随机数
int old = rand() % 9 + 1;
//比较输入的和随机数是否相同
printf("old:%d\n", old);
if (temp != old)
{
printf("错误 退出!\n");
exit(EXIT_SUCCESS);
}
}
printf("正确!\n");
}
return 0;
}
- 思路:首先产生一组随机数存储在缓冲区,再一个一个输入数字,一个一个与对应位置数字进行比对,因此利用到循环,来接受用户一个一个输入。
- 如何进行比对?这就需要两次生成的随机数完全一致,
- 感悟:要对随机数的产生有自己的理解,学会利用随机数;编写代码要有逻辑性。