为什么随机数发生器的数字大小有限?

esr*_*sra 1 c++ random numbers generator

我已经编写了一个随机数生成器srand(),它创建了一个给定大小的随机数数组.我想我的随机数值取值高达1000.000并得到这个,我已经定义了数组的每个条目,如rand()%1000000下面的代码所示.奇怪的是,随机值都高达30.000左右,并且没有创建更大的随机数,如987.623,即随机数的数字数不超过5.有没有人知道为什么会发生这种情况?是否有其他方法(功能)可以提供比这些更大的随机数?

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <time.h>
#include <cmath>
#include <vector>
using namespace std;

int * rng(int size) {
    int* a = NULL;
    a = new int[size];
    for (int i = 0; i < size; i++) {
        a[i] = rand() % 1000000;
        if (a[i] == 0) {
            a[i] += 1;
        }
    }
    for (int j = 0; j < size; j++) {
        cout << a[j] << " ";
    }
    delete[] a;
    a = NULL;
    return a;
}

int main() {   
    srand(time(NULL)); 
    int size;
    int* x;
    ifstream myfile("size.txt");
    ofstream outfile("input.txt");
    while (myfile>>size) {   
        x=rng(size);
        if (outfile.is_open()) {    
            for(int count = 0; count < size; count ++) {
                outfile<< x[count] << " " ;
            } 
        myfile.close();
        }       
    }
    return 0;
    delete [] x;  
    x = NULL;
}
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 6

您机器上的RAND_MAX显然接近或达到标准允许的最小值:32767.

有很多替代品可以提供更好的周期性.Mersenne Twister就是这样一个很好的选择,它构成了C++ 11标准的一部分.

另请注意,返回语句后的语句无法访问.考虑一下

std::vector<int>
Run Code Online (Sandbox Code Playgroud)

作为返回类型.