如果您在没有先调用srand() 的情况下调用rand(),它的行为就像您已经隐式调用了srand(1)。标准C99 7.20.2.2 The srand function(cstdlib 所基于)的相关位指出:
如果在调用 srand 之前调用了 rand,则应生成与第一次调用 srand 时相同的序列,种子值为 1。
换句话说,您将每次都得到相同的序列。您可以将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 种可能性),输出的“随机”性质意味着它也可能在此之前重复 :-)