zoukankan      html  css  js  c++  java
  • c/c++ 随机数生成

    当程序需要一个随机数时有两种情况下使用:

      1.程序中只需使用一次随机数,则调用rand()函数即可

      2.程序需要多次使用随机数,那么需要使用srand()函数生成随机数种子在调用rand()函数保证每次的随机数不同

    原因:rand()函数生成的是一个伪随机数列,生成随机数依据随机数种子,如果随机数种子相同那么每次生成的随机数也会相同。在不同的使用情况下需要注意用法。

    用法实例:

     1   #include <iostream> 
     2   #include <stdlib.h> 
     3   #include <time.h> 
     4   
     5   using namespace std; 
     6   
     7   int main() //一次使用随机数
     8   {       
     9          cout << rand() << '	'; 
    10          cout << endl; 
    11          return 0; 
    12  }
     1 #include <iostream> 
     2 #include <stdlib.h> 
     3 #include <time.h> 
     4 
     5 using namespace std; 
     6 
     7 int main() //多次使用随机数
     8 { 
     9         srand((unsigned)time(NULL)); //设置随机数种子,time(NULL)是用来获取当前系统时间,srand()以每次当前系统时间保证随机数种子不同,使每次产生的随机数不同
    10         for(int i = 0; i < 10;i++ ) 
    11                 cout << rand() << '	'; 
    12         cout << endl; 
    13         return 0; 
    14 }
  • 相关阅读:
    python之jupyter
    python处理图片
    python之图片指纹(唯一性的)
    python之操作elasticsearch7.6.0
    elasticsearch之索引
    elasticsearch
    Nginx 出现 403 Forbidden解决方案
    centos 防火墙命令
    centos nginx常用的命令
    搭建centos nginx环境
  • 原文地址:https://www.cnblogs.com/spring-hailong/p/6106014.html
Copyright © 2011-2022 走看看