产生随机数的方法

在C/C++中,如果想要产生一个随机数,需要用到的是rand()函数和srand()函数


rand()函数返回0~RAND_MAX(32767)的整数。

  1. 产生随机数,不设定范围
#include 
using namespace std;

int main()
{
	int n = rand();
	cout << n << endl;
	return 0;
}
  1. 产生对应范围内的随机数
#include 
using namespace std;

int main()
{
	// [0,99]
	int n = rand()%100;
	cout << n << endl;
	return 0;
}

srand()函数就是用来设置rand()函数的种子的。根据不同的参数产生不同的种子。只使用rand()函数时默认的种子为1,所以下一次访问的时候还是第一次产生的随机数的值。

srand()函数定义: void srand (unsigned int seed);

随机数一般会采用时间来作为种子,因为时间一直在变化,就需要用到time()函数。

time()函数定义: time_t time(time_t *t);

time()函数需要的头文件是 #include

#include 
#include  
using namespace std;
int main()
{
	srand(time(NULL));
	//srand((int)time(0));
	for(int i = 0; i < 20; i++)
		cout << rand() << endl;
	system("pause");
	return 0;
}

你可能感兴趣的:(C++)