C++不用ctime和random生成随机数
时间: 2024-05-12 22:15:10 浏览: 17
在C++中可以使用`<random>`头文件中的随机数生成器来生成随机数,以下是一个示例代码:
```cpp
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 6);
for(int i = 0; i < 10; i++)
{
std::cout << dis(gen) << " ";
}
std::cout << std::endl;
return 0;
}
```
上述代码使用了`std::random_device`来获取一个随机种子,然后使用`std::mt19937`作为随机数生成器,最后使用`std::uniform_int_distribution<>`指定了生成的随机数的范围为1~6之间的整数。在循环中调用`dis(gen)`即可生成随机数。
相关问题
C++不用ctime生成随机数
可以使用C++11中的`<random>`头文件中的随机数生成器来生成随机数,这种方法比使用`ctime`更为安全和高效。以下是一个例子:
```c++
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 6);
for (int i = 0; i < 10; ++i) {
std::cout << dis(gen) << ' ';
}
std::cout << std::endl;
return 0;
}
```
`std::random_device`是一个设备,用于生成真正的随机数种子。`std::mt19937`是一个随机数生成器,使用Mersenne Twister算法生成随机数。`std::uniform_int_distribution`是一个分布,它将随机数分布在指定的范围内。
这个例子中,我们使用`std::uniform_int_distribution`生成一个1到6之间的随机整数,并将其输出到控制台。
c++如何生成随机数
C++中生成随机数的方法有多种,其中常用的有两种方法:
1.使用rand()函数生成随机数,需要包含头文件<cstdlib>和<ctime>,并使用srand()函数初始化随机数种子。示例代码如下:
```
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand((unsigned)time(NULL)); // 初始化随机数种子
for(int i=0; i<10; i++) {
cout << rand() << ' '; // 生成随机数
}
return 0;
}
```
2.使用C++11标准库中的随机数生成器,需要包含头文件<random>,并使用std::default_random_engine生成随机数引擎,std::uniform_int_distribution生成随机数分布。示例代码如下:
```
#include <iostream>
#include <random>
using namespace std;
int main() {
random_device rd; // 随机数种子
default_random_engine eng(rd()); // 随机数引擎
uniform_int_distribution<int> distr(1, 100); // 随机数分布
for(int i=0; i<10; i++) {
cout << distr(eng) << ' '; // 生成随机数
}
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)