美文网首页
生成随机数

生成随机数

作者: KinKen | 来源:发表于2018-12-30 12:16 被阅读0次

    两个C函数

    rand()函数生成的随机数是伪随机数,所谓伪随机数,指的是程序每次运行,生成的随机数都是不变的,生成随机数的原理是根据一个种子,用某个递推公式推算出一系列数,而种子值是计算机开启后固定的,除非重置了计算机。

    rand()返回一随机数,范围在0~RAND_MAX之间,RAND_MAX在stdlib.h定义,这个值会根据环境变化。一般在调用rand()前,会使用srand()来设置随机数种子让rand()每次生成的随机数变化,如果没有设置,则默认使用1。

    一般用法:
    1.使用srand()提供一个种子,参数是一个unsigned int,一般可以用时间作为参数,如srand(time(NULL)),因为程序运行时间不同。

    2.调用rand(),根据上面提供的种子返回一个随机数(范围在0~RAND_MAX);

    3.多次调用rand(),获取随机数

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int* arrayWithRandom(int length) {
        srand((unsigned int)time(NULL));//time(NULL)返回当前时间距离1970年1月1日的时间间隔,单位秒数
        int *array = (int *)malloc(sizeof(int) * length);
        for (int i = 0; i < length; i++) {
            array[i] = rand()%100;
        }
        return array;
    }
    
    int main(int argc, const char * argv[]) {
        int *array = arrayWithRandom(10);
        for (int i = 0; i < 10; i++) {
            printf("%d ",array[i]);
        }
        return 0;
    }
    
    递归求解调用过程

    相关文章

      网友评论

          本文标题:生成随机数

          本文链接:https://www.haomeiwen.com/subject/gxkvlqtx.html