6

采取以下程序:

#include <cstdlib>
using std::rand;

#include <iostream>
using std::cout;

int main()
{
    cout << rand() << ' ' << rand() << ' ' << rand() << '\n';
}

由于rand只要不使用 更改种子就产生相同的值srand,这应该产生三个相同的数字。
例如

567 567 567

然而,当我运行这个程序时,它给了我三个不同的值。
例如

6334 18467 41

当程序再次(编译并)运行时,会生成相同的三个数字。srand在我开始得到不同的结果之前,我不应该使用改变种子rand吗?这只是我的编译器/实现试图帮我一个忙吗?

操作系统:Windows XP
编译器:GCC 4.6.2
库:MinGW

编辑:通过尝试使用srand,我发现这是种子 1 的结果(我猜这是默认值)。

4

2 回答 2

4

Calling rand() multiple times intentionally produces a different random number each time you call it.

Unless your program calls srand() with a different value for each run, the sequence will be the same for each run.

You could use srand() with the time to make the entire sequence different each time. You can also call srand() with a known value to reset the sequence - useful for testing.

See the documentation for rand() and srand().

于 2012-04-05T16:22:45.940 回答
4

Each call to rand() will always generate a different random number.

The seed actually determines the sequence of random numbers that's created. Using a different seed will get you another 3 random numbers, but you will always get those 3 numbers for a given seed.

If you want to have the same number multiple times just call rand() once and save it in a variable.

于 2012-04-05T16:23:44.427 回答