c++10个随机数生成
时间: 2023-10-16 14:28:22 浏览: 144
以下是生成10个随机数的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int i, num;
srand(time(NULL)); // 设置随机数种子
printf("生成的随机数为:\n");
for (i = 0; i < 10; i++) {
num = rand(); // 生成随机数
printf("%d\n", num);
}
return 0;
}
```
以上代码使用了 `srand()` 函数设置随机数种子,并使用 `rand()` 函数生成随机数。每次运行程序都会生成不同的随机数序列。
相关问题
c++怎么结束随机数生成
在 C++ 中,可以使用 srand() 函数来初始化随机数生成器,使用 rand() 函数来生成随机数。如果需要结束随机数生成,可以使用 srand() 函数将随机数生成器重新初始化为一个特定的值,例如 0。这样做可以确保下一次生成的随机数序列与上一次不同。
以下是一个示例代码:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
// 初始化随机数生成器
srand(time(NULL));
// 生成随机数
int random_number = rand() % 100;
std::cout << "Random number: " << random_number << std::endl;
// 结束随机数生成
srand(0);
// 再次生成随机数
random_number = rand() % 100;
std::cout << "Random number: " << random_number << std::endl;
return 0;
}
```
c++正太分布随机数生成
可以使用C++标准库中的<random>头文件中的normal_distribution类来生成正态分布随机数。具体实现代码如下:
```c++
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> dis(0, 1); // 均值为0,标准差为1的正态分布
for (int i = 0; i < 10; ++i) {
std::cout << dis(gen) << ' ';
}
std::cout << std::endl;
return 0;
}
```
其中,std::random_device用于获取真正的随机数种子,std::mt19937是一个高质量的随机数生成器,std::normal_distribution是正态分布随机数生成器。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)