C++ int float casting

后端 未结 8 1542

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

    Because (a.y - b.y) is probably less then (a.x - b.x) and in your code the casting is done after the divide operation so the result is an integer so 0.

    You should cast to float before the / operation

    0 讨论(0)
  • 2020-12-09 08:37

    if (a.y - b.y) is less than (a.x - b.x), m is always zero.

    so cast it like this.

    float m = ((float)(a.y - b.y)) / ((float)(a.x - b.x));
    
    0 讨论(0)
提交回复
热议问题