zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    MAX导致数据库超时
    mysql查询效率提高技巧
    微信回调报文解析, 获取请求体内容
    炖汤秘方
    首字母小写
    List分页
    HttpServletRequest通过InputStream获取参数
    github命令行
    mysql死锁
    分布式锁-redis
  • 原文地址:https://www.cnblogs.com/woaiheniunai/p/6035396.html
Copyright © 2011-2022 走看看