c++_生成随机数

用rand()的函数,生成随机数,头文件<cstdlib>

该函数需要一个起始种子,若没有指定该种子,则每次运行时会产生相同的数字流

#include <stdio.h>
#include <cstdlib>
#include <ctime>

int main()
{
	printf("time:%ld\n", time(0));

	for (int i = 0; i < 10; i++)
	{
		int num = rand();
		printf("num:%d\n", num);
	}

	system("pause");
	return 0;
}

 

 用time的函数获取种子,time(0)函数返回当前格林尼治标准时间与格林尼治标准时间1970年0分0秒的时间间隔。头文件<ctime>。

time(0)  和  time(NULL)的功能相同。

#include <stdio.h>
#include <cstdlib>
#include <ctime>

int main()
{
	unsigned seed;
	seed = time(0);
	srand(seed);	//为随机数生成器提供一个种子

	for (int i = 0; i < 10; i++)
	{
		int num = rand();
		printf("num:%d\n", num);
	}

	//生成[1,max_n]之间的随机数
	int max_n = 13;
	int out_n = rand() % max_n + 1;
	printf("[1,max_n] out_n:%d\n", out_n);

	//生成[min_n,max_n]之间的随机数
	int min_n = 5;
	out_n = rand() % (max_n - min_n + 1) + min_n;
	printf("[min_n,max_n] out_n:%d\n", out_n);

	system("pause");
	
	return 0;
}

 生成指定长度的随机字符串

#include <stdio.h>
#include <cstdlib>
#include <ctime>
#include <string>

std::string rand_str(int len)
{
	std::string str = "";
	for (int i = 0; i < len; ++i)
	{
		switch ((rand() % 3))
		{
		case 1:
			str += ('A' + rand() % 26);
			break;
		case 2:
			str += ('a' + rand() % 26);
			break;
		default:
			str += ('0' + rand() % 10);
			break;
		}
	}
	return str;
}

int main()
{
	srand((unsigned)time(0));

	for (int i = 0; i < 10; i++)
	{
		std::string str = rand_str(13);
		printf("%s\n", str.c_str());
	}

	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值