21xrx.com
2025-04-17 23:41:14 Thursday
文章检索 我的文章 写文章
C++生成0-1随机数的方法
2023-07-05 05:16:06 深夜i     43     0
C++ 生成 0-1 随机数 方法

在C++中,生成0-1随机数的方法有很多种。下面介绍几种常用的方法。

1. 使用rand函数

rand函数是C++标准库中的一个随机数函数。它返回一个0到RAND_MAX之间的随机整数。我们可以使用rand() % 2的方式来生成0-1随机数。具体代码如下:

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
  srand((unsigned)time(NULL)); // 随机数种子,以当前时间为基准
  for (int i = 0; i < 10; i++) {
    int num = rand() % 2; // 生成0-1随机数
    cout << num << " ";
  }
  return 0;
}

2. 使用C++11的random库

C++11的random库提供了生成随机数的各种算法和工具类。我们可以使用uniform_int_distribution函数来生成0-1随机数。具体代码如下:

#include <iostream>
#include <random>
using namespace std;
int main() {
  random_device rd;
  mt19937 gen(rd());
  uniform_int_distribution<> dis(0, 1); // 生成0-1随机数
  for (int i = 0; i < 10; i++) {
    int num = dis(gen);
    cout << num << " ";
  }
  return 0;
}

3. 使用bitset类

bitset是C++标准库中的一个类,用于表示二进制位集合。我们可以使用它的随机数函数来生成0-1随机数。具体代码如下:

#include <iostream>
#include <bitset>
using namespace std;
int main() {
  bitset<1> b; // 创建一个包含1位的bitset对象
  for (int i = 0; i < 10; i++) {
    b = bitset<1>(rand() & 1); // 生成0-1随机数
    cout << b.to_ulong() << " ";
  }
  return 0;
}

总之,C++生成0-1随机数的方法有很多种,我们可以根据自己的需求选择合适的方法来生成随机数。

  
  

评论区

请求出错了