我的随机数生成器出了什么问题?

时间:2020-12-09 03:58:45

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). 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?

我只是潜入一些C ++,我决定制作一个随机数生成器(数字是多么随机,这无关紧要)。大多数代码都是从网上复制出来的,但是我的新手眼睛看不出有什么问题,有什么办法可以调整一下,每次给出一个除“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;
    }
}

3 个解决方案

#1


Add srand before the loop

在循环之前添加srand

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

#2


Don't call srand() within random_number(). 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.

不要在random_number()中调用srand()。这将在每次调用时重新播种随机数生成器。对于100次通话,您很可能在每次通话时获得相同的种子,因此数字相同。

#3


The problem is that you use srand everytime. CPU is so fast that it will execute all this code in a single second, so you get the same seed each time.

问题是你每次都使用srand。 CPU非常快,它会在一秒钟内执行所有这些代码,因此每次都可以获得相同的种子。

Move srand out of the loop, call it only once.

将srand移出循环,只调用一次。

#1


Add srand before the loop

在循环之前添加srand

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

#2


Don't call srand() within random_number(). 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.

不要在random_number()中调用srand()。这将在每次调用时重新播种随机数生成器。对于100次通话,您很可能在每次通话时获得相同的种子,因此数字相同。

#3


The problem is that you use srand everytime. CPU is so fast that it will execute all this code in a single second, so you get the same seed each time.

问题是你每次都使用srand。 CPU非常快,它会在一秒钟内执行所有这些代码,因此每次都可以获得相同的种子。

Move srand out of the loop, call it only once.

将srand移出循环,只调用一次。