为什么每次运行程序时,我的"随机"生成的数字都在增加?
Why are my 'randomly' generated numbers are increasing every time I run the program?
我试图通过使用srand()
和rand()
来获得随机生成的数字,但没有值:每次我运行程序时,它都会增加一定数量的数字。但是如果我使用for
语句,则看不到任何模式。
42
52
72
78
85
92
12 (it has reset)
32
48
注意:我注意到一个奇怪的事情,当我取消聚焦或最小化Visual Studio
并关闭命令提示符时,下次我运行程序时,该数字增加了20多个,但是,如果我不取消聚焦或最小化Visual Studio
,该数字增加了1-5多一点。为什么?
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand (time(NULL));
int random_number = rand () % 100 + 1;
cout << "Random number: " << random_number << endl;
return 0;
}
但是,如果我使用这段代码:
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand (time(NULL));
for (int i = 0; i < 10; i++) {
int random_number = rand () % 100 + 1;
cout << "Random number: " << random_number << endl;
}
return 0;
}
数字没有清晰的模式,我得到输出:
31
10
81
66
74
14
6
97
39
23
它们以随机数量随机增加和减少。这里有什么问题吗?
某些版本的rand
(看看你的微软)返回的前几个随机数与它们开始的种子高度相关,只是由于使用了随机数生成器公式。由于两次运行之间的时间变化不大,随机数也不会改变。如果你扔掉返回的前几个随机数,你可以得到更好的结果。
一个更好的解决方案是使用std::uniform_int_distribution
代替rand
。
另一个潜在的问题是rand的一些实现可能与某些模块交互不良。出于这个原因,您可能需要考虑这样做:
int v = ((double)rand() / (double)RAND_MAX) * 100 + 1;
仍然不理想,但很容易。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 数组索引的值没有增加
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 为什么我的代码在输出中增加了93天
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 在C++中增加大数字(近 100.000 位)
- 有效数字在增加
- 如何设置QSqlQueryModel的Qt::Vertical headerData在进行分页时增加数字
- 在c或c++中,将字母数字字符串abcd1234增加到abcd2000
- 增加递归函数中的数字
- 为什么每次运行程序时,我的"随机"生成的数字都在增加?
- 无法在C++中增加程序中的数字范围
- 程序与数组来检查增加/减少的数字
- 为什么 C++ 中的编译器不增加循环中最后一个数字的值?
- 如何增加一个数字,停止它,在C++上使用 if/else 语句