关于c++随机种子srand( time(NULL) )的设置问题

设置随机种子srand( time(NULL) ) ,在程序中只需要设置一次就好,而且不能被调用多次,直接看列子。

a:每次都重新设置随机种子

 1 #include<iostream>
 2 #include<cstdlib>
 3 #include<ctime>
 4 #include<cmath>
 5 using namespace std;
 6 void fun() 
 7 {
 8     srand((unsigned)time(NULL));//每次都重新设置随机种子
 9     cout << rand() << endl;
10 }
11 int main()
12 {
13     for (int i = 0; i < 5; i++)
14         fun();
15     system("pause");
16     return 0;
17 }

结果:每次结果是一样的。

b:只设置一次随机种子

 1 #include<iostream>
 2 #include<cstdlib>
 3 #include<ctime>
 4 #include<cmath>
 5 using namespace std;
 6 void fun() 
 7 {
 8     cout << rand() << endl;
 9 }
10 int main()
11 {
12     srand((unsigned)time(NULL));//设置一次随机种子
13     for (int i = 0; i < 5; i++)
14         fun();
15     system("pause");
16     return 0;
17 }

结果:得到想要的效果。

猜你喜欢

转载自www.cnblogs.com/suchang/p/10550309.html