• srand()、rand()、time()函数的用法


    srand()就是给rand()提供种子seed。

    如果srand每次输入的数值是一样的,那么每次运行产生的随机数也是一样的。

    以一个固定的数值作为种子是一个缺点。通常的做法是 :以这样一句srand((unsigned) time(NULL));来取代,这样将使得种子为一个不固定的数,这样产生的随机数就不会每次执行都一样了。详细用法如下:

     1 #include <iostream>
     2 #include <stdlib.h>
     3 #include <time.h>
     4 using namespace std;
     5 int main()
     6 {
     7     /*Seed the random-number generator with current time 
     8     so that the numbers will be different every time we run.*/
     9     srand((unsigned)time(NULL));
    10     
    11     /* Display 10 numbers */
    12     for(int i=0;i<10;i++)
    13     {
    14         cout<<rand()<<endl;
    15     }
    16     return 0;
    17 }

    rand(void)用于产生一个伪随机unsigned int 整数。 
    srand(seed)用于给rand()函数设定种子。

    srand 和 rand 应该组合使用。一般来说,srand 用于对 rand 进行设置。 
    比如:

    #include <iostream>
    #include <cstdlib>
    #include <time.h>
    using namespace std;
    int main()
    {
        srand(time(0));
        /* Display 10 numbers */
        for(int i=0;i<10;i++)
        {
            cout<<rand()%100<<endl;
        }
        return 0;
    }
  • 相关阅读:
    (4.12)全面解析-SQL事务+隔离级别+阻塞+死锁
    【生产问题】--8KW的数据表导致业务卡顿
    (4.6)数据页深入探索--内部探索聚集索引
    (4.11)DBCC 常用命令
    数据库设计与性能优化
    有些事女人忍受不了
    android系列控件
    java常量
    context startactivity
    AssetManager
  • 原文地址:https://www.cnblogs.com/woaiheniunai/p/6035396.html
Copyright © 2020-2023  润新知