相同的随机数

时间:2012-11-13 03:46:07

标签: c++ random srand

  

可能重复:
  Same random numbers every loop iteration

这是我的代码:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int attack() {
    srand((unsigned)time(NULL));
    int hits=0;
    for (int i=0;i<=3;i++) {
        int a = rand() % 6;
        if (a==6 || a==5)
        {
         hits++;   
        }
    }
    return hits;
}

int main () {
    int a=attack();
    cout << a << endl;
    int b=attack();
        cout << b << endl;
    int c=attack();
        cout << c << endl;
    int d=attack();
        cout << d << endl;
    int e=attack();
        cout << e << endl;
    int f=attack();
        cout << f << endl;
    int g=attack();
        cout << g << endl;
    int h=attack();
        cout << h << endl;
}

为什么main()中的所有变量都是相同的数字?

我只得到这样的输出:

1
1
1
1
1
1
1
1

1 个答案:

答案 0 :(得分:3)

srand()应该在程序开始时调用一次(好吧,在你开始调用rand()之前的某个时刻)。

每次进入函数时都会调用它(快速连续),你将种子值重置为同一个东西,这就是你看到重复数字的原因。

请注意,如果在程序运行时点击一个新的秒,可能偶尔会得到一个不同的数字,但由于该特定程序应该远远少于一个,所以不太可能第二

在第一次致电srand()之前,将main()来电转至attack()