不引用rand相关函数,完成抽奖序列生成c++,并给出代码
时间: 2024-05-04 19:22:09 浏览: 17
以下是一个简单的无重复抽奖序列生成的C++代码示例:
```
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n; // 抽奖总人数
cout << "请输入抽奖总人数:";
cin >> n;
// 初始化抽奖序列
vector<int> lotterySeq(n);
for (int i = 0; i < n; i++) {
lotterySeq[i] = i + 1;
}
// 随机打乱抽奖序列
random_shuffle(lotterySeq.begin(), lotterySeq.end());
// 输出抽奖序列
cout << "抽奖序列为:" << endl;
for (int i = 0; i < n; i++) {
cout << lotterySeq[i] << " ";
}
cout << endl;
return 0;
}
```
该代码使用STL中的`vector`和`random_shuffle`函数实现,首先初始化抽奖序列为1到n,然后使用`random_shuffle`函数随机打乱序列,最后输出结果。
相关问题
不引用rand相关函数和random库生成 随机数c++并给出代码
可以使用C++11中的<random>库来生成随机数。下面是一个生成0到100之间随机整数的示例代码:
```c++
#include <iostream>
#include <random>
int main() {
std::random_device rd; // 从硬件获得种子
std::mt19937 gen(rd()); // 用 Mersenne Twister 引擎生成随机数
std::uniform_int_distribution<> dis(0, 100); // 生成0到100之间的随机整数
std::cout << dis(gen) << std::endl; // 输出一个随机整数
return 0;
}
```
在上面的代码中,我们使用了`std::random_device`来获取真正的随机数种子,并使用`std::mt19937`引擎来生成随机数。然后,我们使用`std::uniform_int_distribution`来指定生成随机整数的范围。最后,我们通过调用`dis(gen)`来生成随机整数,并将其输出到控制台。
不引用rand相关函数,用for循环生成 随机数c++并给出代码
可以使用当前的时间作为随机数生成器的种子,然后借助取模运算生成一个随机序列。以下是一个生成随机数的示例代码:
```c++
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// 使用当前时间作为随机数生成器的种子
srand(time(nullptr));
// 生成10个随机数
for (int i = 0; i < 10; i++) {
int rand_num = rand() % 100; // 生成0~99之间的随机数
cout << rand_num << " ";
}
return 0;
}
```
这段代码将会生成10个0~99之间的随机数,并将它们输出到控制台上。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)