c++ - 如何使 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 << "";
}
}
解决方案
问题不在于rand
,而在于您没有打印您认为正在打印的数字。
您向向量添加一个数字,然后对向量进行排序,然后打印向量的最后一个数字,这不一定是您刚刚添加的数字 - 它始终是您刚刚排序后最大的数字。
先生成整个向量,然后排序并打印出来,你会看到更多的随机性。
(并且在 中调用srand
一次,main
因此您永远不会意外地多次调用。)
推荐阅读
- java - How large should my list of objects be to warrant the use of java 8's parallelStream?
- arrays - 如何使用密钥从 json 中提取对象?
- vba - VBA Word:您可以将类、标签或名称分配给范围以独立于表格格式访问它们吗?
- spring - Spring Boot 2 数据 JPA:事务不回滚
- python - 如何对列表元素的值求和,哪些元素的值来自熊猫中的 anthor 数据框?
- android - 强制 LinearLayout 子级使用所有可用空间,但至少足以容纳其内容
- azure - K8 Ingress 没有端点
- c++ - 操作失败,没有当前记录。异常类:CDBException,错误:1007
- java - 将文件生成到不同的包 pom.xml
- python - SQLAlchemy 关系:查找具有一个或多个共同属性的实例