C++随机数rand(), srand()

2023-02-12,,

c++产生随机数会用到rand(), srand()函数,下面总结两个函数特性和使用。

1. rand()

#include <iostream>
#include <cstdlib>
using namespace std; int main()
{
int m; for(int i = 1; i <= 5; i++)
{
m = rand();
cout << "m = " << m << endl;
} return 0;
}

2. srand()

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std; int main()
{
int m;
srand((unsigned)time(NULL)); for(int i = 1; i <= 5; i++)
{
m = rand();
cout << "m = " << m << endl;
} return 0;
}

3. 产生一定范围随机数的公式

获取[a,b)的随机整数,使用(rand() % (b-a))+ a; 
获取[a,b]的随机整数,使用(rand() % (b-a+1))+ a; 
获取(a,b]的随机整数,使用(rand() % (b-a))+ a + 1; 
获取0~1之间的浮点数,可以使用rand() / double(RAND_MAX)

[参考文章:如有侵权,请告知,立即删除]

1. http://www.cnblogs.com/afarmer/archive/2011/05/01/2033715.html

2. http://blog.csdn.net/peixuan197/article/details/48084843

C++随机数rand(), srand()的相关教程结束。

《C++随机数rand(), srand().doc》

下载本文的Word格式文档,以方便收藏与打印。