[英]rand() function generates the next number by ascending to the previous number
请检查下面给出的代码。 它为每次执行生成的随机数是上一次执行中生成的数字的增量。
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(NULL));
cout<<"\n Random Number : "<<rand()<<endl;
cin.get();
return 1;
}
请执行 5-6 次,您会看到每次执行的随机数都在增加,并且它们非常接近。
注意:请使用 CodeBlocks 或 Visual Studio 来检查它,而不是在线编译器。
实际上,我找到了解决问题的方法,但它仍然可能不是我问题的答案。 无论如何,问题不在于srand()
或rand()
函数,而在于函数time(NULL)
。 由于我试图在 Windows 上运行此代码,而不是使用time(NULL)
作为srand()
的参数,我使用了GetTickCount()
,现在它为每次执行正确生成随机数。
#include <iostream>
#include <cstdlib>
#include <windows.h>
using namespace std;
int main()
{
srand(GetTickCount());
cout<<"\n Random Number : "<<rand();
cout<<"\n";
cin.get();
return 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.