在C语言编程中,经常会用到随机数,所以总结一下rand()和srand()两个随机数的生成函数
- rand()会生成一个位于0~RAND_MAX之间的整数;rand()函数产生的随机数是伪随机数,是根据一个数值按照某个公式推算出来的,这个数值称之为 “种子”。种子和随机数之间的关系是一种正太分布,种子在每次启动计算机时是随机的,但是一旦计算机启动以后它就不再变化了;也就是说,每次启动计算机以后,种子就是定值了,所以根据公式推算出来的结果(也就是生成的随机数)就是固定的。
下面是一个随机数生成的实例:
include <stdio.h>
include <stdlib.h>
int main(){
int a = rand();
printf("%d\n",a);
return 0;
}
- srand()函数是根据时间作为参数,只要每次播种的时间不同,那么生成的种子就不同,最终的随机数也就不同。使用 <time.h> 头文件中的 time() 函数即可得到当前的时间(精确到秒),就像下面这样:
srand((unsigned)time(NULL));
对上面的代码进行修改,生成随机数之前先进行播种:
include <stdio.h>
include <stdlib.h>
include <time.h>
int main() {
int a;
srand((unsigned)time(NULL));
a = rand();
printf("%d\n", a);
return 0;
}
多次运行程序,会发现每次生成的随机数都不一样了。但是,这些随机数会有逐渐增大或者逐渐减小的趋势,这是因为我们以时间为种子,时间是逐渐增大的,结合上面的正态分布图,很容易推断出随机数也会逐渐增大或者减小。
一定范围内的随机数:
int a = rand() % 10; //产生0~9的随机数,注意10会被整除
一组随机数(多个随机数)
include <stdio.h>
include <stdlib.h>
include <time.h>
int main() {
int a, i;
//使用for循环生成10个随机数
for (i = 0; i < 10; i++) {
srand((unsigned)time(NULL));
a = rand();
printf("%d ", a);
}
return 0;
}