产生随机数的方法

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


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

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

int main()
{
	int n = rand();
	cout << n << endl;
	return 0;
}
  1. 产生对应范围内的随机数
#include <iostream>
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<time.h>

#include <iostream>
#include <time.h> 
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值