C++ int float casting

后端 未结 8 1540

Why is m always = 0? The x and y members of someClass are integers.

float getSlope(someClass a, someClass b)
{           
    float m = (a.y - b.y) / (a.x -         


        
8条回答
  •  执念已碎
    2020-12-09 08:24

    Integer division occurs, then the result, which is an integer, is assigned as a float. If the result is less than 1 then it ends up as 0.

    You'll want to cast the expressions to floats first before dividing, e.g.

    float m = (float)(a.y - b.y) / (float)(a.x - b.x);
    

提交回复
热议问题