C ++ rand()在运行进程时给出相同的数字 [英] C++ rand() gives same number when running process
问题描述
示例:
#include< iostream&
#include< math.h>
using namespace std;
void wait(){
int e;
cin>> e;
}
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 <随机(2,5)<< endl;
wait();
}
输出:
3
5
4
2
3
每次运行程序时,每次都输出相同的数字。
未设置随机数生成器的种子
如果你调用srand(time(NULL)),你会得到更多的随机结果:
#include< iostream>
#include< cstdlib>
#include< ctime>
using namespace std;
int main(){
srand(time(NULL));
cout<< rand()<< endl;
return 0;
}
原因是从rand()函数生成的随机数isn' t实际随机。它只是一种变换。维基百科更好地解释了伪随机数发生器的含义:确定性随机位发生器。每次调用rand()它需要种子和/或最后生成的随机数(C标准没有指定使用的算法,虽然C ++ 11有指定一些流行的算法的功能),运行对这些数字进行数学运算,并返回结果。所以如果种子状态是相同的每一次(因为如果你不调用srand一个真正的随机数字),那么你总是会得到相同的随机数字。
如果您想了解更多,可以阅读以下内容:
http://www.dreamincode.net/forums/topic/24225-random-number-generation-102/
I am fairly new to C++ and have a question about rand()
every time I run a process with rand() it gives me the same results
example :
#include <iostream>
#include <math.h>
using namespace std;
void wait () {
int e;
cin >> e;
}
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;
wait ();
}
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(time(NULL)) then you will get more random results:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(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/
这篇关于C ++ rand()在运行进程时给出相同的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!