How do I scale down numbers from rand()?

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

    Some people have posted the following code as an example:

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

    This is an invalid way of solving the problem, as both rand() and RAND_MAX are integers. In C++, this results in integral division, which will truncate the results decimal points. As RAND_MAX >= rand(), the result of that operation is either 1 or 0, meaning rawRand can be only 0 or 100. A correct way of doing this would be the following:

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

    Since one the operands is now a double, floating point division is used, which would return a proper value between 0 and 1.

提交回复
热议问题