首页 > 技术文章 > C/C++ 生成随机数

zhanjiahui 2021-02-05 20:10 原文

time stdlib math 三个库

srand种子

rand() 生成随机整数 范围[0,RAND_MAX]整数

RAND_MAX 与系统环境有关 可能为32767

 

//生成随机数算法笔记P144
#include<time.h>
#include<stdlib.h>
#include<math.h>//round
#include<iostream>
using namespace std;
int main()
{
    srand((unsigned)time(NULL));

    //左右端点之差不超过RAND_MAX的小随机数
    int p= rand()%(35-21+1) + 21;
    cout<<p<<endl;
    
    //左右断点之差大于RAND_MAX的大随机数
    int q=(int)(round(1.0*rand()/RAND_MAX*(60000-50000)+50000));
    cout<<q<<endl;

    return 0;
}

 

推荐阅读