Generate random float between two floats

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

    float RandomFloat(float min, float max)
    {
        // this  function assumes max > min, you may want 
        // more robust error checking for a non-debug build
        assert(max > min); 
        float random = ((float) rand()) / (float) RAND_MAX;
    
        // generate (in your case) a float between 0 and (4.5-.78)
        // then add .78, giving you a float between .78 and 4.5
        float range = max - min;  
        return (random*range) + min;
    }
    

提交回复
热议问题