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

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

posted on 2017-05-02 18:14  zhongqing  阅读(358)  评论(0编辑  收藏  举报