問題描述
每次我用 rand()
運行程序時,它都會給我相同的結果.
示例:
#include #include 使用命名空間標準;int隨機(int低,int高){如果(低>高)回報高;返回低 + (rand() % (高 - 低 + 1));}int main (int argc, char* argv []) {for (int i = 0; i <5; i++)cout<<隨機 (2, 5) <<結束;}
輸出:
35423
每次我運行程序時,它每次都會輸出相同的數字.有沒有辦法解決這個問題?
未設置隨機數生成器的種子.
如果你調用 srand((unsigned int)time(NULL))
那么你會得到更多的隨機結果:
#include #include #include <ctime>使用命名空間標準;int main() {srand((unsigned int)time(NULL));cout<<蘭特()<<結束;返回0;}
原因是從 rand()
函數生成的隨機數實際上并不是隨機的.這簡直就是一種轉變.維基百科對偽隨機數生成器的含義給出了更好的解釋:確定性隨機位生成器.每次調用 rand()
時,它都會獲取生成的種子和/或最后一個隨機數(C 標準沒有指定使用的算法,盡管 C++11 具有指定一些流行的算法),對這些數字運行數學運算,并返回結果.因此,如果種子狀態每次都相同(就像您不使用真正的隨機數調用 srand
一樣),那么您將始終得到相同的隨機"數.>
如果您想了解更多,可以閱讀以下內容:
http://www.dreamincode.net/forums/topic/24225-random-number-generation-102/
http://www.dreamincode.net/forums/topic/29294-making-pseudo-random-number-generators-more-random/
Every time I run a program with rand()
it gives me the same results.
Example:
#include <iostream>
#include <cstdlib>
using namespace std;
int random (int low, int high) {
if (low > high)
return high;
return low + (rand() % (high - low + 1));
}
int main (int argc, char* argv []) {
for (int i = 0; i < 5; i++)
cout << random (2, 5) << endl;
}
Output:
3
5
4
2
3
Each time I run the program it outputs the same numbers every time. Is there a way around this?
The seed for the random number generator is not set.
If you call srand((unsigned int)time(NULL))
then you will get more random results:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand((unsigned int)time(NULL));
cout << rand() << endl;
return 0;
}
The reason is that a random number generated from the rand()
function isn't actually random. It simply is a transformation. Wikipedia gives a better explanation of the meaning of pseudorandom number generator: deterministic random bit generator. Every time you call rand()
it takes the seed and/or the last random number(s) generated (the C standard doesn't specify the algorithm used, though C++11 has facilities for specifying some popular algorithms), runs a mathematical operation on those numbers, and returns the result. So if the seed state is the same each time (as it is if you don't call srand
with a truly random number), then you will always get the same 'random' numbers out.
If you want to know more, you can read the following:
http://www.dreamincode.net/forums/topic/24225-random-number-generation-102/
http://www.dreamincode.net/forums/topic/29294-making-pseudo-random-number-generators-more-random/
這篇關于為什么 rand() 每次運行都會產生相同的數字序列?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!