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

· · 算法·理论

1. rand()和srand()

示例:

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

2.random

示例:

#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

示例:

#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.硬件随机数

示例:

#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

示例:

#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;
}