如果在调用
srand()
之前调用
rand()
,它将隐式地被视为已经调用了
srand(1)
。 标准
C99 7.20.2.2
(
cstdlib
基于该标准)中的相关部分如下所述:
如果在任何对srand的调用之前调用rand,则将生成与首次使用种子值1调用srand时相同的序列。
换句话说,每次都会得到相同的序列。您可以将您的main
更改为:
int main (int argc, char* argv []) {
srand (time (0)); // needs ctime header.
for (int i = 0; i < 5; i++)
cout << random (2, 5) << endl;
wait ();
}
要解决这个问题,假设你不会在一秒内运行它超过一次。
如前所述,你需要使用 ctime
头文件。你还应该引入 cstdlib
,因为那里有 rand
和 srand
。通常最好使用 cXXX
的头文件而不是 XXX.h
的头文件(例如使用 cmath
而不是 math.h
)。
因此,在进行所有这些更改后(并且使用显式命名空间,我喜欢但其他人可能不喜欢),最终代码会是:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
void wait () {
int e;
std::cin >> e;
}
int random (int low, int high) {
if (low > high) return high;
return low + (std::rand() % (high - low + 1));
}
int main (int argc, char* argv []) {
std::srand (std::time (0));
for (int i = 0; i < 5; i++)
std::cout << random (2, 5) << '\n';
wait ();
}
每次运行该程序,它都会给出一个不同的序列,至少在运行几次之后是这样的。显然,数据重复的硬性限制存在(只有45种可能性),而输出的“随机”性质也意味着它可能在此之前就会重复:-)
srand()
,否则我无法获得相同的序列。如果不调用srand()
,序列就不会重复。这是在gcc(Debian 12.2.0-14)12.2.0下的情况。 - undefined