What's wrong with my random number generator?

2019-02-21 05:06发布

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

标签: c++ random
3条回答
老娘就宠你
2楼-- · 2019-02-21 05:22

Add srand before the loop

 srand((unsigned)time(0));
  for(int i =0;i < 100;i++)
    {
        std::cout << random_number(3,10) << endl;
    }
查看更多
Anthone
3楼-- · 2019-02-21 05:44

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.

查看更多
Juvenile、少年°
4楼-- · 2019-02-21 05:49

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.

查看更多
登录 后发表回答