学习记录:随机数
与随机相关的函数定义在stdilib.h头文件中,常用的有:
rand():根据种子给出一个随机的数字;
srand():为函数rand()设置种子,括号里填写一个unsigned类型的数据;
习题:
在某单位1000名职工中,征集慈善募捐,当总数达到10万元时就结束,统计此时捐款的人数,以及捐款人平均每人捐款的数目。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
printf("每人捐款6到16元");
int money,count=0, sum=0, n;
srand((unsigned)time(NULL);
for (n=1; n<=1000;n++) {
money = rand()%11+6;
sum+=money;
count++;
if(sum>=100000) break;
}
if(n==1000&&sum<100000) printf("钱不够啊!");
printf("一共%d人捐款,平均捐款%.2f元。",count,1.0*sum/count);
return 0;
}
}
1.关于rand()给的值
使用srand设置种子时,使用了time(),time()能给出一个时间相关的值;
当种子固定时,使用rand()得到的随机数就固定了,例如运行下面的程序,连续取十次rand()的值:
#include <stdio.h>
#include <stdlib.h>
int main() {
srand(2);
for(int i=1;i<=10;i++){
int a=rand();
printf("%d\n",a);
}
}
不管运行多少次,输出的结果都为:
45
29216
24198
17795
29484
19650
14590
26431
10705
18316
若将srand(2)放进for循环里,那么a每次循环都是rand()取得的第一个值,即是45。
#include <stdio.h>
#include <stdlib.h>
int main() {
for(int i=1;i<=10;i++){
srand(2);
int a=rand();
printf("%d\n",a);
}
}
45
45
45
45
45
45
45
45
45
45
由此可见,rand()给出的数字与srand规定的种子的值和取值的次数相关。另外,当没有srand()规定种子的值时,产生的数字与种子为1产生的相同。
2.关于srand()括号内的值
语法:void srand (unsigned seed);
参数说明:unsigned seed:随机数产生器的初始值(种子值)
功能说明:srand设置产生一系列伪随机数发生器的起始点,要想把发生器重新初始化,可用作seed值。任何其它的值都把发生器匿成一个随机的起始点。rand检索生成的伪随机数。在任何调用srand之前调用rand与以1作为seed调用srand产生相同的序列。
此函数可以设定rand函数所用的随机数产生演算法的种子值。任何大于一的种子值都会将rand随机数所产生的虚拟随机数序列重新设定一个起始点。
关于unsigned的解释可以看博客园的一篇文章
当srand()内填写字符类型的数据时,会用这个字符的ASCLL值来计算
#include <stdio.h>
#include <stdlib.h>
int main() {
srand(')');
for(int i=1;i<=10;i++){
int a=rand();
printf("%d\n",a);
}
}
右括号‘)’的ASCLL值为41;结果是这个:
172
22420
5
5992
5768
8953
4904
10571
32065
7917
当srand()内填写负数时,居然还可以正常运行,就离谱,以后再看看能不能理解这是为什么
#include <stdio.h>
#include <stdlib.h>
int main() {
srand(-1);
for(int i=1;i<=10;i++){
int a=rand();
printf("%d\n",a);
}
}
结果:
35
29739
3374
11141
31308
7870
5253
2445
26706
3992