zoukankan      html  css  js  c++  java
  • C语言 产生随机数

    rand()函数

    #include <stdlib.h>
    int rand(void);
    

    rand()是根据某个种子,以特定的算法,计算出一系列数的函数。返回的数在0和RAND_MAX之间。RAND_MAX定义在stdlib.h中,至少是32767。

    然而,这生成的是伪随机数,因为种子在计算机开机后就设定好了,所以这一系列数都是可预测的,每次得出的数列都是相等的。想要得到真正的随机数,必须重新设定这个种子。

    srand()函数

    #include <stdlib.h>
    void srand(unsigned int seed);
    

    srand(seed)是C语言中,用于设定随机数种子的函数,通常用时间作为seed,每次运行的时间都不同,所以产生的随机数种子也不同。srand(time(NULL))

    如何产生随机数

    1. 调用srand(time(NULL)),设置随机数种子
    2. 反复调用rand(), 产生随机数
    #include <stdlib.h>
    #include <stdio.h>
    #include <time.h>           
     
    void main( void )
    {
      int i;
      srand((unsigned)time(NULL));          
        for(i = 0; i < 10; i++) {                          
            printf("%d
    ", rand());
        }
    }
    
  • 相关阅读:
    dubbo springcloud区别
    rpc
    centos7 安装docker
    vibox安装
    知识点
    spring cloud
    微服务设计原则
    工具类
    xss--知识点
    java基础--注解
  • 原文地址:https://www.cnblogs.com/shenlinken/p/9404570.html
Copyright © 2011-2022 走看看