首页 > 解决方案 > 如何使 rand() 更随机?

问题描述

所以我有一个使用向量生成随机数的程序,从技术上讲它可以工作,但每次我运行程序时,它都会给我数字,比如 22 22 34 34 34 34 34 或 13 13 30 30 30 30 30。所以它给了我每次都有不同的数字,但不是真的。每次获得完全随机数的任何帮助。

#include <iostream>
#include <random>
#include <algorithm>
#include <cstdlib>
#include <time.h>
#include <vector>
using namespace std;

void regular();
void bonus();

int main() {
    regular();
    //bonus();
}


void regular() {
    cout << "These are your regular numbers." << endl;
    int i = 0;
    vector<int> regs;
    srand(time(NULL));
    for (i = 0; i < 7; i++) {
        int x = rand() % 39 + 1;
        regs.push_back(x);
        sort(regs.begin(), regs.end());
        cout << regs[i] << " ";
    }
    cout << endl;
}


void bonus() {
    cout << "These are your bonus numbers." << endl;
    int i = 0;
    srand(time(0));
    for (i = 0; i < 7; i++) {
        cout << rand() % 39 + 1 << "";
    }
}

标签: c++random

解决方案


问题不在于rand,而在于您没有打印您认为正在打印的数字。

您向向量添加一个数字,然后对向量进行排序,然后打印向量的最后一个数字,这不一定是您刚刚添加的数字 - 它始终是您刚刚排序后最大的数字。

先生成整个向量,然后排序并打印出来,你会看到更多的随机性。

(并且在 中调用srand一次,main因此您永远不会意外地多次调用。)


推荐阅读