问题描述:

int RandomNum(int n, int nMax)

{

srand(time(NULL));

int r = 1 + rand() % nMax;

while (r == n)

{

r = 1 + rand() % nMax;

}

return r;

}

int _tmain(int argc, _TCHAR* argv[])

{

for (int i = 0; i < 10; i++)

{

int x=RandomNum(4, 100);

std::cout << x << "\n";

}

return 0;

}

Is my VS13 going wild or what because it is always outputting the same number in every execution of the code above ? Debugging shows the output display different numbers but one time run does not :(

网友答案:

The loop is short, and will loop over all values within a single second. That causes all your calls to rand to start with the same seed.

Only call srand once, preferably very early in the main function.

网友答案:

You‘re specyfing the seed every time. Instead you have to do it only once.

Move srand(time(NULL)) to the beginning of main.

相关阅读:
Top