What's wrong with my random number generator?

2019-02-21 05:30发布

问题:

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?

#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;
    }
}

回答1:

Add srand before the loop

 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.



回答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.

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



标签: c++ random