c++生成随机数详解(包含可执行代码)
1.rand
c++中生成随机数最简单的方式就是rand函数。而且rand函数位于stdlib.h头文件中,不需要额外的再引入。
int rand(void) __swift_unavailable("Use arc4random instead.");
从rand的函数签名不难看出其返回的是一个int类型。
#include<iostream> #include<ctime> using namespace std; void run1() { for(int i=0; i<3; i++) { std::cout<<"rand() is: "<<rand()<<std::endl; } std::cout<<"RAND_MAX is: "<<RAND_MAX<<std::endl; }
run1方法的输出为
rand() is: 16807 rand() is: 282475249 rand() is: 1622650073 RAND_MAX is: 2147483647
2.srand
rand函数生成的是伪随机数。伪随机数的意思是,不管运行多少次,每次运行的结果都是一致的。为了解决伪随机数的问题,可以采用srand函数。
srand的函数签名为
void srand(unsigned) __swift_unavailable("Use arc4random instead.");
可见要想使用srand,需要传入一个unsigned类型,一般就可以使用time方法。
void run2() { srand((unsigned)time(NULL)); for(int i=0; i<3; i++) { std::cout<<"srand() is: "<<rand()<<std::endl; } }
上述输出为
srand() is: 1462514084 srand() is: 376386226 srand() is: 1583959967
3.生成一定区间的整数
上面的分析我们看出rand函数返回的是int整数,如果我们想要返回一定范围内的整数,该怎么办? c++中没有直接相关的内置函数,不过我们可以通过简单的方式就可以满足上面的要求。
3.1 生成[a,b)左开右闭区间整数
可以直接套用公式rand()%(a-b) + a 上面的公式也很好理解,rand()%(a-b)的范围是[0, b-a),则[0, b-a) + a的范围就是[a, b)
// 生成[0, 2)区间整数,也就生成0或者1 void run3() { srand((unsigned)time(NULL)); int count0 = 0, count1 = 0; for(int i=0; i<10000; i++) { int num = (rand() % (2 - 0)) + 0; if (num == 0) count0++; else if (num == 1) count1++; } cout<<"count0 is: "<<count0<<endl; cout<<"count1 is: "<<count1<<endl; }
代码运行结果为
count0 is: 4996 count1 is: 5004
3.2 生成(a,b]左闭右开区间整数
公式为rand()%(a-b) + a +1
void run4() { srand((unsigned)time(NULL)); int count1 = 0, count2 = 0; for(int i=0; i<10000; i++) { int num = (rand() % (2-0)) + 0 + 1; if (num == 1) count1++; else if (num == 2) count2++; } cout<<"count1 is: "<<count1<<endl; cout<<"count2 is: "<<count2<<endl; }
3.3 生成[a,b]闭区间
公式为rand() % (b-a+1) + a
void run5() { srand((unsigned)time(NULL)); int count0 = 0, count1 = 0, count2 = 0; for(int i=0; i<10000; i++) { int num = (rand() % (2-0+1)) + 0; if (num == 0) count0++; else if (num == 1) count1++; else if (num == 2) count2++; } cout<<"count0 is: "<<count0<<endl; cout<<"count1 is: "<<count1<<endl; cout<<"count2 is: "<<count2<<endl; }
4.生成浮点数
平时还经常需要生成0-1之间的浮点数表示概率,可以直接使用公式 rand() / RAND_MAX 注意的是c++整数除法为取整,所以需要将其转成double类型。
void run6() { srand((unsigned)time(NULL)); for(int i=0; i<10; i++) { cout<<(double)rand()/RAND_MAX<<endl; } }
0.68945 0.578391 0.0133102 0.704486 0.291283 0.590195 0.398975 0.569631 0.794225 0.54148
上一篇:
IDEA上Java项目控制台中文乱码