C++实现随机数生成

C++实现随机数生成

1. 包含文件

实现随机数需要<cstdlib>
实现随机数种子需要<ctime>,即利用系统时间生成随机数种子
其他文件:
实现输入输出流,需要<iostream>
实现格式化输出,需要<iomanip>

2. 相关函数

rand()函数:生成一个伪随机数
srand((int)time(NULL))srand((int)time(0)):利用系统时间生成随机数种子
生成[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)

RAND_MAX是一个大数,一般是0x7fff

3. 示例代码

#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <ctime>

using namespace std;

void test1()
{
	cout << "生成[0, 100)的随机数(伪随机数):" << endl;
	for (int i = 0; i < 10; i++)
	{
		cout << rand() % 100 << " ";
	}
	cout << endl;
}

void test2()
{
	cout << "生成[0, 100)的随机数(利用系统时间生成随机数种子):" << endl;
	srand((int)time(NULL));
	for (int i = 0; i < 10; i++)
	{
		cout << rand() % 100 << " ";
	}
	cout << endl;
}

#define random1(x) rand()%(x)
void test3()
{
	cout << "生成[0, 100)的随机数:" << endl;
	srand((int)time(NULL));
	for (int i = 0; i < 10; i++)
	{
		cout << random1(100) << " ";
	}
	cout << endl;
}

#define random2(a,b) (rand()%(b-a)) + a
void test4()
{
	cout << "生成[a, b)的随机数: a = 5, b = 10" << endl;
	srand((int)time(NULL));
	for (int i = 0; i < 10; i++)
	{
		cout << random2(5, 10) << " ";
	}
	cout << endl;
}

#define random3(a,b) (rand()%(b-a+1)) + a
void test5()
{
	cout << "生成[a, b]的随机数: a = 5, b = 10" << endl;
	srand((int)time(NULL));
	for (int i = 0; i < 10; i++)
	{
		cout << random3(5, 10) << " ";
	}
	cout << endl;
}

#define random4(a,b) (rand()%(b-a)) + a + 1
void test6()
{
	cout << "生成(a, b]的随机数: a = 5, b = 10" << endl;
	srand((int)time(NULL));
	for (int i = 0; i < 10; i++)
	{
		cout << random4(5, 10) << " ";
	}
	cout << endl;
}

#define random5() (rand() / double(RAND_MAX))
void test7()
{
	cout << "生成0~1的随机浮点数:(保留四位小数)" << endl;
	srand((int)time(NULL));
	for (int i = 0; i < 10; i++)
	{
		cout << setiosflags(ios::fixed) << setprecision(4)<< random5() << " ";
	}
	cout << endl;
}


int main(int argc, char** argv)
{
	test1();
	test2();
	test3();
	test4();
	test5();
	test6();
	test7();
	system("pause");
}
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值