C++ int float casting

后端 未结 8 1571

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:27

    When doing integer division, the result will always be a integer unless one or more of the operands are a float. Just type cast one/both of the operands to a float and the compiler will do the conversion. Type casting is used when you want the arithmetic to perform as it should so the result will be the correct data type.

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

提交回复
热议问题