How do I scale down numbers from rand()?

后端 未结 9 1893
小蘑菇
小蘑菇 2020-11-27 14:38

The following code outputs a random number each second:

int main ()
{
    srand(time(NULL)); // Seeds number generator with execution time.

    while (true)         


        
相关标签:
9条回答
  • 2020-11-27 15:20

    See man 3 rand -- you need to scale by dividing by RAND_MAX to obtain the range [0, 1] after which you can multiply by 100 for your target range.

    0 讨论(0)
  • 2020-11-27 15:22

    int rawRand = rand() % 101;
    

    See (for more details):

    rand - C++ Reference

    Others have also pointed out that this is not going to give you the best distribution of random numbers possible. If that kind of thing is important in your code, you would have to do:

    int rawRand = (rand() * 1.0 / RAND_MAX) * 100;
    

    EDIT

    Three years on, I'm making an edit. As others mentioned, rand() has a great deal of issues. Obviously, I can't recommend its use when there are better alternatives going forward. You can read all about the details and recommendations here:

    rand() Considered Harmful | GoingNative 2013

    0 讨论(0)
  • 2020-11-27 15:24

    rawRand % 101 would give [0-100], inclusive.

    0 讨论(0)
提交回复
热议问题