C++ generating random numbers

后端 未结 11 1621
我寻月下人不归
我寻月下人不归 2020-12-01 10:49

My output is 20 random 1\'s, not between 10 and 1, can anyone explain why this is happening?

#include  
#include  
#include <         


        
11条回答
  •  长情又很酷
    2020-12-01 11:21

    Because, on your platform, RAND_MAX == INT_MAX.

    The expression range*rand() can never take on a value greater than INT_MAX. If the mathematical expression is greater than INT_MAX, then integer overflow reduces it to a number between INT_MIN and INT_MAX. Dividing that by RAND_MAX will always yield zero.

    Try this expression:

    random_integer = lowest+int(range*(rand()/(RAND_MAX + 1.0)))
    

提交回复
热议问题