我試圖通過使用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
它們增加和減少隨機隨機數量。這裏似乎是什麼問題?
有點不清楚。你是否因爲隨機數字是隨機的而感到困惑? –
你的第二個例子似乎更隨機,因爲你重新使用相同的種子(如你應該),而不是基於快速連續的[幾乎]相同的輸入生成新的種子。 – TZHX
它們在使用第二個代碼片段時是隨機的,但在使用第一個代碼片段時它們不是隨機的(它們增加了一定數量的數字並且不減少;僅重置)。 –