【发布时间】:2016-09-16 22:18:46
【问题描述】:
我试图通过使用srand() 和rand() 来获得随机生成的数字,但没有avale:每次我运行程序时,它都会增加一定数量的数字。但如果我使用for 语句,则看不到任何模式。
例如,如果我使用下面提供的代码并运行和关闭程序 10 次,输出将是:
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
它们以随机数量随机增加和减少。这里似乎有什么问题?
【问题讨论】:
-
有点不清楚。你是否因为你的随机数是随机的而感到困惑?
-
您的第二个示例似乎更加随机,因为您正在重复使用相同的种子(正如您应该使用的那样),而不是根据 [几乎] 相同的输入快速连续生成新的种子。跨度>
-
在使用第二个代码 sn-p 时它们是随机的,但在使用第一个代码 sn-p 时并不完全随机(它们增加了一定数量的数字并且不会减少;仅重置)。
-
但是您的第一组示例数字与您描述的不同。我看到它们在您的列表中增加和减少。您的 10 次运行输出列表与您的第二个 sn-p 具有相同的特征。它不是每次都增加相同的数量。
-
@JasonC 完成...