【问题标题】:How to make rand() more random?如何使 rand() 更随机?
【发布时间】:2020-01-20 09:06:30
【问题描述】:

所以我有一个使用向量生成随机数的程序,从技术上讲,它可以工作,但每次我运行程序时,它都会给我一些数字,例如 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


【解决方案1】:

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

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

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

(并在main 中调用srand 一次,这样您就不会意外地多次这样做。)

【讨论】:

  • 问题在于,如果我这样做并将 sort 和 cout 内容移出 for 循环,我会收到一条错误消息,提示 Debug Assertion Failed。
  • @Jaakko 如果发生这种情况,你做错了,应该发布另一个问题,询问它有什么问题。
  • 是的,我刚刚意识到出了什么问题并且它正在工作。谢谢。
猜你喜欢
  • 2020-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多