简体   繁体   English

我的随机数生成器怎么了?

[英]What's wrong with my random number generator?

I'm just diving into some C++ and I decided to make a random number generator (how random the number is, it really doesn't matter). 我只是学习一些C ++,所以我决定制作一个随机数生成器(数字有多随机,这真的没关系)。 Most of the code is copied off then net but my newbie eyes cannot see anything wrong with this, is there any way this can be tweaked to give a number other than "6" each time? 大部分代码是从网络上复制下来的,但是我的新手眼睛看不到有什么问题,是否可以通过任何方式对此进行调整以给出除“ 6”以外的数字?

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;
int random_number(int min, int max)
{
    srand((unsigned)time(0));
    int random_num;
    int range=(max-min)+1;
    random_num = min+int(range*rand()/(RAND_MAX + 1.0)); 
    return random_num;
}
int main()
{
    for(int i =0;i < 100;i++)
    {
            cout << random_number(3,10) << endl;
    }
}

Don't call srand() within random_number(). 不要在random_number()中调用srand()。 This will re-seed the random number generator every call. 这将在每次调用时重新填充随机数生成器。 For 100 calls, you'll very likely get the same seed every call, and therefore the same number. 对于100个通话,您很可能在每个通话中获得相同的种子,因此编号也相同。

Add srand before the loop 在循环之前添加srand

 srand((unsigned)time(0));
  for(int i =0;i < 100;i++)
    {
        std::cout << random_number(3,10) << endl;
    }

The problem is that you use srand everytime. 问题是您每次都使用srand。 CPU is so fast that it will execute all this code in a single second, so you get the same seed each time. CPU是如此之快,以至于它可以在一秒钟内执行所有这些代码,因此您每次都获得相同的种子。

Move srand out of the loop, call it only once. 将srand移出循环,仅调用一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM