【发布时间】: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 << "";
}
}
【问题讨论】:
-
不要使用
rand(),使用标准中的Random Number Distribution。例如std::uniform_int_distribution. -
顺便说一句,实际上您似乎想要随机排列(用于彩票模拟)。
std::shuffle可能是想要的(然后取第一个数字)。 -
@Timo -- 尽管有言辞,
rand()在许多情况下都非常有效。尤其是在回应初学者时,请绝对清楚您的建议会分散注意力,不会解决他们的问题。不要让初学者陷入困境。