用c ++生成随机数

时间:2018-06-10 05:00:30

标签: c++ random

所以我试图在一个程序执行中生成3组10个随机数,但是当我运行程序时,第一组中的10个数字是随机的,但第二组和第三组的数字是与第一组相同,甚至是序列。 我想知道是因为我使用srand(time(0))来生成种子,并且因为整个程序在一秒钟内运行,所以我调用的3个rand函数使用相同的种子。如果是这样的话,他们无论如何都要解决这个问题吗?

干杯

这是我的代码:

     #include "stdafx.h"
     #include "iostream"
     #include "cstdlib"
     #include "ctime"

     using namespace std;
int main()
{
int b = 0;
srand((int) time(0));
cout << "Test 1: " << endl;

for (int a = 0; a < 10; a++)
{

    b = rand();

    cout << b << endl;


}
cout << endl;
cout << endl;

cout << "Test 2: " << endl;
srand((int)time(0));

for (int a = 0; a < 10; a++)
{
    b = rand();

    cout << b << endl;

}
cout << endl;
cout << endl;

cout << "Test 3: " << endl;
srand((int)time(0));

for (int a = 0; a < 10; a++)
{
    b = rand();

    cout << b << endl;

}


return 0;

}

0 个答案:

没有答案
相关问题