C ++ int浮动铸造 [英] C++ int float casting

查看:190
本文介绍了C ++ int浮动铸造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么m always = 0? someClass的x和y成员是整数。

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 - b.x);
    cout << " m = " << m << "\n";
    return m;
}


推荐答案

结果,是整数,被分配为float。如果结果小于1,那么它最终为0.

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);

这篇关于C ++ int浮动铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆