相同的随机数

Same random numbers

本文关键字:随机数      更新时间:2023-10-16

可能的重复:
相同的随机数每个循环迭代

这是我的代码:

#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

srand()应该在程序开始时称为(好吧,在您开始调用rand()之前的某个时候)。

每次输入函数时(快速连续)调用它,您将种子值重置为同一事物,这就是为什么您会看到重复数字。

请注意,如果您的程序运行时,您的 May 偶尔会获得其他数字第二。

在第一个呼叫attack()之前,将srand()调用到main()