我是靠谱客的博主 缓慢悟空,这篇文章主要介绍C语言中的伪随机数rand()和真随机数srand(),现在分享给大家,希望可以做个参考。

  • 随机数函数rand()

    函数rand()其实是一个伪随机数生成器,为什呢?

    复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    //rand()函数的内核算法 static unsigned long int next = 1;//种子 unsigned int rand(void{ /*生成伪随机数的魔术公式*/ next = next * 1103515245 + 12345; return (unsigned int) (next / 65536) % 32768; }

    不难看出,每次调用函数rand(),他的初始化种子都是从1 开始。这就说明虽然他得到的数是随机的,但是关闭程序再次运行得到的随机数又都是一样的。这可真糟糕!如何做到真真的随机呢?

    复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    //srand()函数的内核算法 static unsigned long int next = 1;//种子 unsigned int rand(void{ /*生成伪随机数的魔术公式*/ next = next * 1103515245 + 12345; return (unsigned int) (next / 65536) % 32768; } void srand(unsigned int seed) { next=seed; }

    不难看出,只需要每次运行程序的时候把种子变一下,不让他从1开始,就达到了随机的效果。。。。

    有一个方法,可以每次都随机种子,她就是srand((unsigned int)tine(0));

    复制代码
    1
    2
    3
    4
    5
    6
    #include<stdio.h> #include<time.h> #include<stdlib.h> srand((unsigned int )time(0));

    一般而言,time()函数接受的参数是一个time_t类型对象的地址,而时间值就存储在传入的地址上,当然,也可以传入空指针(0)作为参数,这种情况下,只能通过返回值机制来提供值。

    复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    //srand() demo int main() { int a,b,c,d; //每次种子都会发生变化,得到的值就是一个随机的 srand((unsigned int)(time(0))); for(int i=0;i<5;i++){ a=rand()%100; b=rand()%100; c=rand()%100; d=rand()%100; printf("%dn%dn%dn%d",a,b,c,d); } }

    给大家里留一个思考题,我看看多少人可以答对?

    思考:如果把srand((unsigned int)(time(0)))放在循环开头会是怎么样呢?代码我放在下面了,欢迎大家在评论区作答

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
int main() { int a,b,c,d; for(int i=0;i<5;i++){ srand((unsigned int)(time(0))); a=rand()%100; b=rand()%100; c=rand()%100; d=rand()%100; printf("%dn%dn%dn%d",a,b,c,d); } }

最后

以上就是缓慢悟空最近收集整理的关于C语言中的伪随机数rand()和真随机数srand()的全部内容,更多相关C语言中内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(81)

评论列表共有 0 条评论

立即
投稿
返回
顶部