How do I scale down numbers from rand()?

后端 未结 9 1982
小蘑菇
小蘑菇 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:18

    How long an answer would you like.

    the simplest is to convert using the remainder when divided by 101:

    int value = rawRand % 101;
    

    A semipurist would rescale using doubles:

    double dbl = 100 * ((double)rawRand / RAND_MAX);
    int ivalue = (int)(dbl + 0.5);   // round up for above 0.5
    

    And a purist would say that rand does not produce random numbers.

    For your info, the quality of random numbers is measured by taking a sequence of numbers and then calculating the mathematical probability that the source of that sequence was random. The simple hack using the remainder is a very poor choice if you are after randomness.

提交回复
热议问题