C++怎么产生随机数
时间: 2024-06-13 22:06:57 浏览: 19
C++中产生随机数有两种方法:使用C语言的方法和使用C++11提供的随机数库。
1.使用C语言的方法
C语言中使用rand()函数生成随机数,需要包含头文件stdlib.h。具体实现方法如下:
```c
#include <stdlib.h>
#include <time.h>
int main()
{
int random_num;
srand((unsigned)time(NULL)); // 用当前时间作为随机数种子
random_num = rand(); // 生成随机数
return 0;
}
```
2.使用C++11提供的随机数库
C++11提供了更加灵活的随机数生成方法,包括随机数生成器和随机数分布器。具体实现方法如下:
```c++
#include <random>
int main()
{
std::random_device rd; // 用于获取随机数种子
std::mt19937 gen(rd()); // 用mt19937作为随机数生成器
std::uniform_int_distribution<> dis(1, 6); // 用uniform_int_distribution作为随机数分布器,生成1到6之间的整数
int random_num = dis(gen); // 生成随机数
return 0;
}
```
相关问题
c++产生随机数的函数
C++标准库提供了一个可以产生随机数的函数rand(),需要包含头文件<cstdlib>。具体使用方法如下:
1. 使用srand()函数来初始化随机数种子。可以使用当前时间作为种子来保证随机性。
```c++
#include <cstdlib> // 包含rand()和srand()函数
#include <ctime> // 包含time()函数
#include <iostream>
int main() {
srand(time(NULL)); // 初始化随机数种子
std::cout << rand() << std::endl; // 产生随机数
return 0;
}
```
2. 直接调用rand()函数来产生随机数。需要注意的是,每次调用rand()函数产生的随机数都是伪随机数,所以需要在使用之前先调用srand()函数来初始化随机数种子。
```c++
#include <cstdlib> // 包含rand()函数
#include <iostream>
int main() {
std::cout << rand() << std::endl; // 产生随机数,此时随机数种子未初始化,结果相同
std::cout << rand() << std::endl; // 产生随机数,此时随机数种子未初始化,结果相同
srand(123); // 初始化随机数种子
std::cout << rand() << std::endl; // 产生随机数,此时随机数种子已初始化,结果不同
std::cout << rand() << std::endl; // 产生随机数,此时随机数种子已初始化,结果不同
return 0;
}
```
c++数组乱序c++产生随机数
c 数组乱序可以通过生成随机数来实现。常用的算法是使用Fisher-Yates算法(也称为Knuth-Durstenfeld Shuffle算法)。该算法的基本原理是从数组的最后一个元素开始,每次随机选择一个索引,然后将该索引对应的元素与当前位置的元素进行交换。然后继续从剩下的元素中选择一个索引,重复这个过程,直到数组中的所有元素都被遍历一次。这样就完成了数组的乱序。
以下是c语言实现乱序算法的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void shuffle(int a[], int n) {
srand(time(NULL));
for (int i = n - 1; i > 0; i--) {
int j = rand() % (i + 1);
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
int main() {
int a[] = {1, 2, 3, 4, 5};
int n = sizeof(a) / sizeof(a[0]);
shuffle(a, n);
for (int i = 0; i < n; i++) {
printf("%d ", a[i]);
}
return 0;
}
```
这段代码中,我们使用srand函数以系统时间作为种子来初始化随机数生成器。然后通过rand函数生成一个介于0和i之间的随机索引j。然后将a[i]与a[j]进行交换。重复这个过程,直到所有的元素都被遍历一次。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)