Generate random float between two floats

前端 未结 4 1079
陌清茗
陌清茗 2021-02-03 22:03

I know this is a rather simple question, but I\'m just not too good at maths.

I know how to generate a random float between 0 and 1:

float random = ((flo         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-02-03 22:43

    Suppose, you have MIN_RAND and MAX_RAND defining the ranges, then you can have the following:

    const float MIN_RAND = 2.0, MAX_RAND = 6.0;
    const float range = MAX_RAND - MIN_RAND;
    float random = range * ((((float) rand()) / (float) RAND_MAX)) + MIN_RAND ;
    

    This will provide you the number scaled to your preferred range. MIN_RAND, MAX_RAND can be any value, like say 2.5, 6.6 So, the function could be as:

    float RandomFloat(float min, float max) {
        return  (max - min) * ((((float) rand()) / (float) RAND_MAX)) + min ;
    }
    

提交回复
热议问题