为什么我们要分别投射到“浮动"?在整数除法中? [英] Why do we separately cast to "float" in an integer division?

查看:29
本文介绍了为什么我们要分别投射到“浮动"?在整数除法中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

int number1 = 1, number2= 2;
float variable = (float)number1/(float)number2;

取而代之的是,为什么我们不能只使用一次浮动"?例如:

Instead of this, Why can't we use "float" only once? For example:

int number1 = 1, number2= 2;
float variable = (float)(number1/number2);

推荐答案

目标是避免整数除法带来的截断.这要求至少一个除法运算的操作数是浮点数.因此,您只需要对 float 进行一次强制转换,但要在正确的位置.例如,

The objective is to avoid the truncation that comes with integer division. This requires that at least one of the operands of the division be a floating point number. Thus you only need one cast to float, but in the right place. For example,

float variable = number1/(float)number2; // denominator is float

float variable = ((float)number1)/number2; // numerator is float

请注意,在第二个示例中,为了清楚起见,添加了一组额外的括号,但由于优先级规则,它与

Note that in the second example, one extra set of parentheses has been added for clarity, but due to precedence rules, it is the same as

float variable = (float)number1/number2; // numerator is float, same as above

另请注意,在您的第二个示例中,

Also note that in your second example,

float variable = (float)(number1/number2);

float 的强制转换是在整数除法之后 应用的,因此这并不能避免截断.由于表达式的结果无论如何都分配给了 float,因此它是

the cast to float is applied after the integer division, so this does not avoid truncation. Since the result of the expression is assigned to a float anyway, it is the exact of

float variable = number1/number2;

这篇关于为什么我们要分别投射到“浮动"?在整数除法中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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