Generate random float between two floats

前端 未结 4 1067
陌清茗
陌清茗 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:42

    float RandomFloat(float a, float b) {
        float random = ((float) rand()) / (float) RAND_MAX;
        float diff = b - a;
        float r = random * diff;
        return a + r;
    }
    

    This works by returning a plus something, where something is between 0 and b-a which makes the end result lie in between a and b.

提交回复
热议问题