【问题标题】:Same random numbers [duplicate]相同的随机数[重复]
【发布时间】:2012-11-13 03:46:06
【问题描述】:

可能重复:
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

【问题讨论】:

  • 您应该只初始化 (srand) 一次(在整个程序中,除非您知道自己在做什么以及为什么)并且a = rand() % 6; 永远不会返回 6(但是将返回 0)。有关详细信息,请阅读文档。我知道。我知道:不得已。但你必须这样做。真的。
  • 另一个reading the manual可以避免的问题...
  • 另一个本可以避免的评论...嗯...只是避免...

标签: c++ random srand


【解决方案1】:

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

通过在每次输入函数时调用它(快速连续),您将种子值重置为相同的值,这就是您看到重复数字的原因。

请注意,如果在您的程序运行时时间点击到新的一秒,您可能偶尔会得到一个不同的数字,但这不太可能,因为该特定程序应该在不到一秒的时间内完成第二个。

在第一次调用attack()之前将srand()调用移动到main()

【讨论】:

    猜你喜欢
    • 2013-01-18
    • 1970-01-01
    • 2012-01-16
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2020-02-20
    • 1970-01-01
    相关资源
    最近更新 更多