問題描述
我正在做一個書本練習,內容是編寫一個生成偽隨機數的程序.我從簡單開始.
I'm doing a book exercise that says to write a program that generates psuedorandom numbers. I started off simple with.
#include "std_lib_facilities.h"
int randint()
{
int random = 0;
random = rand();
return random;
}
int main()
{
char input = 0;
cout << "Press any character and enter to generate a random number." << endl;
while (cin >> input)
cout << randint() << endl;
keep_window_open();
}
我注意到每次程序運行時,都會有相同的隨機"輸出.所以我研究了隨機數生成器,并決定通過在 randint() 中首先包含它來嘗試播種.
I noticed that each time the program was run, there would be the same "random" output. So I looked into random number generators and decided to try seeding by including this first in randint().
srand(5355);
它一遍又一遍地生成相同的數字(我現在覺得實現它很愚蠢.)
Which just generated the same number over and over (I feel stupid now for implementing it.)
所以我想我會很聰明并像這樣實現種子.
So I thought I'd be clever and implement the seed like this.
srand(rand());
這基本上和程序最初所做的一樣,但輸出了一組不同的數字(這是有道理的,因為 rand() 生成的第一個數字總是 41.)
This basically just did the same as the program did in the first place but outputted a different set of numbers (which makes sense since the first number generated by rand() is always 41.)
我唯一能想到的讓這更隨機的是:
The only thing I could think of to make this more random is to:
- 讓用戶輸入一個數字并將其設置為種子(這很容易實現,但這是最后的手段)或
- 以某種方式將種子設置為計算機時鐘或其他不斷變化的數字.
我是不是腦子進水了,我現在應該停下來嗎?選項 2 難以實施嗎?還有其他想法嗎?
Am I in over my head and should I stop now? Is option 2 difficult to implement? Any other ideas?
提前致謝.
推薦答案
選項 2 并不難,給你:
Option 2 isn't difficult, here you go:
srand(time(NULL));
你需要為 srand()
包含 stdlib.h
和為 time()
包含 time.h
代碼>.
you'll need to include stdlib.h
for srand()
and time.h
for time()
.
這篇關于在 C++ 中使用 rand() 函數的正確方法是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!