• C random C ++rand函数应用


    random函数不是ANSI C标准,不能在gcc,vc等编译器下编译通过。但在C语言中int random(num)能够这样使用,它返回的是0至num-1的一个随机数。

     可改用C++下的rand函数来实现。

    rand()%n   范围  0~n-1

    rand()主要是实现 产生随机数,其它我们在这里能够无视他

    显然随意 一个数  rand()%n  范围显然是  0~n-1;

    那么 怎样产生 n~m的数呢? 一样的   我们仅仅要对rand()进行一些 符号操作即可了;

    n+rand()%(m-n+1);    这样就能够了

    这样我们 就仅仅有 种子 和 浮点数的没有分析了,

    以下来说rand()的使用方法 ,浮点数的放在最后面讲 :一般在用这个之前 都要  初始化 一个种子 ,可是  你不写的话,系统会给你 一个默认的种子,以下是我们自己输入种子的代码;

    int seed;
    
    scanf ("%d",&seed);
    
    srand(seed);
    
    cout<<rand()<<endl;
    


     

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    int main()
    {
        int arr[15];
        //srand(time(NULL));
        int seed;
        while(1){
        scanf("%d",&seed);
        srand(seed);
        for (int i=0; i<15; i++)
             printf ("%d	",rand()%10);
        printf ("
    ");  
        }
        return 0;
    }

    经过下图的比較发现,每个种子都是保持着这个状态的随机变量值,会存在系统里面;

    因此,我们要对这个初始化种子  保持着  时刻不同;也就是说 我们还是用 srand(time(NULL));比較好

    用例如以下代码比較合适:

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    int main()
    {
        //int arr[15];
        srand(time(NULL));
    	 for (int i=0; i<15; i++)
             printf ("%d	",rand()%10);
        printf ("
    ");  
        while (1);
        return 0;
    }
    


    好了,我们如今讲下最后一点---------浮点数的随机产生

    rand()%n   =========== 0~n-1     那么  我们再除以 n  即可了

    能够表示为:   (rand()%n)/(n*1.0)      //这里注意下 隐式转换   低------>高

    以下给出一个范例:

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    int main()
    {
        int arr[15];
        //srand(time(NULL));
        int seed;
        while(1){
        scanf("%d",&seed);
        srand(seed);
        for (int i=0; i<15; i++)
             printf ("%lf	",(rand()%10)/10.0);
        printf ("
    ");  
        }
        return 0;
    }


    假设要  更精确呢?像0.11  这种呢???   道理是一样的  

     我们能够输出   (rand()%n)/(n*1.0)+(rand()%n)/(n*10.0);

    由此我们能够总结出规律:p 表示精确位数

                                                                      {  p }

                                                                      1.......1*(rand()%n)/10^p                                                                

                                

  • 相关阅读:
    【LeetCode】3Sum Closest 解题报告
    LOJ#6277. 数列分块入门 1
    洛谷P1919 【模板】A*B Problem升级版(FFT快速傅里叶)
    LOJ #108. 多项式乘法
    快速傅里叶变换(FFT)详解
    HDU 5536 Chip Factory
    洛谷P4093 [HEOI2016/TJOI2016]序列
    洛谷P2633 Count on a tree
    HDU 4825 Xor Sum
    洛谷T21778 过年
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4028497.html
Copyright © 2020-2023  润新知