跳到正文

算法·理论

C++生成随机数的五种方法

andy112358约 4 分钟
原文
文章信息与版本

文章信息

发布
2024年9月30日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 4 分钟

版本

  1. v1当前

1. rand()和srand()

  • 库:<cstdlib>和<ctime>(包含在<bits/stdc++.h>中)
  • 优点:最简单的随机数
  • 缺点:生成的是伪随机数,等待时间长,一秒内不可生成多个随机数
  • 评价:★★★☆☆

示例:

C++
#include<cstdib>
#include<ctime>
using namespace std;
int main()
{
    srand(time(0));  //生成随机种子
    int a=rand()%100+1;  //生成1~100的随机数
    cout<<a;
}

2.random

  • 库:<random>(包含在<bits/stdc++.h>中)
  • 优点:不用等太久,一秒内能生成多个随机数
  • 缺点:代码比较复杂,生成的是伪随机数
  • 评价:★★★★☆

示例:

C++
#include<random>
#include<iostream>
using namespace std;
int main()
{
  default_random_engine e;
  uniform_int_distribution<int>u(2,20);
  e.seed(time(0));
  for(int i=0;i<10;i++)
  {
    cout<<u(e)<<endl;
  }
  return 0;
}

3./dev/random和/dev/urandom

  • 库:无
  • 优点:真随机数,完全不用等
  • 缺点:代码太复杂,、如果系统熵池中的熵不够,读取/dev/random可能会阻塞,直到有足够的熵产生。
  • 评价:★★☆☆☆

示例:

C++
#include <stdio.h>
#include <stdlib.h>
using namespace std
int main()
{
  FILE *file = fopen("/dev/urandom", "rb") ;
  unsigned char random_byte;
  if (fread(&random_byte, 1, 1, file) != 1)
  {
    perror ("fread") ;
    exit(EXIT_FAILURE);

    fclose(file);

    int random_number = random_byte % 100;
    cout<<random_number;
  }
  return 0;
}

4.硬件随机数

  • 库:<x86intrin.h>
  • 优点:提供硬件级别的真随机数
  • 缺点:需要多次尝试后才能成功
  • 评价:★★★★☆

示例:

C++
#include <x86intrin.h>
#include <stdio.h>
using namespace std;
int main()
{
  unsigned int random_number;
  _rdrand32_step(&random_number);//可能需要多次尝试才能成功
  cout<<random_number%100;
  return 0;
}

5.OpenSSL

  • 库:<openssl/rand.h>
  • 优点:高质量随机数
  • 缺点:代码过于复杂,部分c++可能不受支持
  • 评价:★★☆☆☆

示例:

C++
#include <openssl/rand.h>
#include <stdio.h>
using namespace std;
int main()
{
  unsigned char random_bytes[4]; //生成 4 字节随机数
  if (!RAND_bytes(random_bytes, sizeof(random_bytes)))
  {
    printf("RAND_bytes failed\n");
    return 1;
  }
  unsigned int random_number = *(unsigned int *) random_bytes;
  cout>>random_number % 100
  return 0;
}
原文