C++实现在一段取值范围内输出不相同的随机数

本文介绍了一个使用C++实现的功能,该功能能够在用户指定的最小值和最大值之间生成10个不重复的随机整数。通过srand和rand函数结合循环检查确保了随机数的唯一性。

输入最小值Min和最大值Max,实现在Min和Max之间输出10个不相同的随机数。

代码如下:

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
const int N = 10;
int* RandNum(int Min, int Max);
int main()
{
	int max, min;
	cout << "Min:";
	cin >> min;
	cout << "Max:";
	cin >> max;
	cout << "Result is:";
	int *a = RandNum(min, max);
	for (int n = 0; n < N; n++)
		cout << a[n] << " ";
	
	cin.get();
	cin.get();
	return 0;
}

int* RandNum(int Min, int Max)
{
	int *t=new int[N];
	srand((unsigned)time(0));
	int i, j;
	for (i = 0; i < N; i++)
	{
		t[i] = Min + rand() % (Max-Min);
		for (j = 0; j < i; j++)
		{
			if (t[i] == t[j])
			{
				i--;
				break;
			}
		}
	}
	return t;
}


程序运行结果:




Protocol Buffers(简称 Protobuf)本身是一种用于据序列化和结构定义的工具,它并直接提供生成随机值的功能。然而,可以通过定义 `.proto` 文件中的字段类型,并结合编程语言的相关库,生成符合时间段内随机取值的逻辑。 例如,假设需要表示一个时间段内的随机时间点,可以使用 `int32` 或 `uint32` 类型来表示时间戳(如 Unix 时间戳),然后在应用程序中生成随机值并赋值给该字段。 ### 示例 `.proto` 定义 ```proto syntax = "proto3"; message TimeRange { uint32 start_time = 1; // 起始时间戳 uint32 end_time = 2; // 结束时间戳 uint32 random_time = 3; // 在时间段内的随机时间点 } ``` ### 生成随机时间点的逻辑(以 Python 为例) ```python import random import time # 生成当前时间的 Unix 时间戳 current_time = int(time.time()) # 定义时间段(例如当前时间往后 1 小时) start_time = current_time end_time = current_time + 3600 # 1 小时后 # 生成时间段内的随机时间点 random_time = random.randint(start_time, end_time) # 构造 Protocol Buffers 消息 time_range = TimeRange() time_range.start_time = start_time time_range.end_time = end_time time_range.random_time = random_time ``` ### 生成随机时间点的逻辑(以 C++ 为例) ```cpp #include <cstdint> #include <cstdlib> #include <ctime> #include "time_range.pb.h" // 假设 TimeRange 的定义在此头文件中 int main() { // 获取当前时间戳 std::time_t current_time = std::time(nullptr); // 定义时间段(例如当前时间往后 1 小时) uint32_t start_time = static_cast<uint32_t>(current_time); uint32_t end_time = start_time + 3600; // 1 小时后 // 生成时间段内的随机时间点 uint32_t random_time = start_time + (std::rand() % (end_time - start_time + 1)); // 构造 Protocol Buffers 消息 TimeRange time_range; time_range.set_start_time(start_time); time_range.set_end_time(end_time); time_range.set_random_time(random_time); return 0; } ``` ### 注意事项 - 时间戳的精度可以根据需求选择(例如毫秒或秒)。 - 随机数生成逻辑需要确保超出定义的时间范围。 - 可以结合 Protocol Buffers 提供的 API 来设置字段值,并序列化为二进制格式进行传输或存储[^5]。 通过这种方式,Protocol Buffers 可以灵活地表示时间段内的随机取值,并结合具体编程语言的随机数生成能力实现所需逻辑。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值