21xrx.com
2024-09-19 10:01:26 Thursday
登录
文章检索 我的文章 写文章
生成随机数的C++代码
2023-07-13 22:31:57 深夜i     --     --
随机数 C++代码 生成 伪随机数 random()函数

在C++编程中,生成随机数是一个很常见的需求。C++提供了许多方法来生成随机数。下面介绍几种常见的方法。

1. 使用rand()函数

rand()函数可以生成0到RAND_MAX之间的随机数。可以通过调用srand()函数设置一个起始值,以在程序每次运行时生成不同的随机数序列。示例代码如下:


#include <iostream>

#include <cstdlib>

#include <ctime>

using namespace std;

int main()

{

  srand(time(NULL)); // 初始化随机数种子

  for (int i = 0; i < 10; i++)

  {

    int rand_num = rand(); // 生成随机数

    cout << rand_num << endl;

  }

  return 0;

}

2. 使用random_shuffle()函数

random_shuffle()函数可以将一组元素随机打乱顺序,从而获得随机数。例如,如果需要在1到100之间生成10个不重复的随机数,可以先将1到100的数字打乱顺序,然后获取前10个数字。代码示例:


#include <iostream>

#include <algorithm>

#include <vector>

#include <ctime>

using namespace std;

int main()

{

  vector<int> nums;

  for (int i = 1; i <= 100; i++)

  {

    nums.push_back(i); // 初始化数字

  }

  srand(time(NULL)); // 初始化随机数种子

  random_shuffle(nums.begin(), nums.end()); // 打乱数字

  for (int i = 0; i < 10; i++)

  {

    cout << nums[i] << endl; // 输出前10个数字

  }

  return 0;

}

3. 使用uniform_real_distribution类

uniform_real_distribution类可以生成在指定范围内的随机浮点数。代码示例:


#include <iostream>

#include <random>

using namespace std;

int main()

{

  random_device rd; // 创建随机数种子

  mt19937 gen(rd()); // 创建随机数生成器

  uniform_real_distribution<double> distr(0.0, 1.0); // 创建随机数分布

  for (int i = 0; i < 10; i++)

  {

    double rand_num = distr(gen); // 生成随机数

    cout << rand_num << endl;

  }

  return 0;

}

这些方法都可以方便地生成随机数,但需要注意的是,生成的随机数并不是真正意义上的“随机”,而是伪随机数。如果需要更加安全的随机数,请使用更为专业的加密算法或随机数生成器。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复