为什么我的 float 类型转换表达式 return 有两个不同的值?
Why does my float type-casting expression return two different values?
以下是我正在使用的表达式:
float firstValue = (float) (5 / 2); //output is 2.0
float secondValue = (float) 5 / 2; //output is 2.5
我被难住了,想不通为什么这种类型转换会返回两个不同的值。我知道我可以做 (5f / 2f)
但我想尝试使用其他类型的表达式进行转换。为什么 firstValue
2.0 而 secondValue
2.5? .5 去哪儿了?
首先是整数数学。这个
float firstValue = (float) (5 / 2);
先用五除以二得二。然后它将 2 转换为 2.0
。第二个是浮点数学。
float secondValue = 5f / 2;
即 2.5(和 float
)。因为 float
除以 int
是 float
.
由于括号具有最高的优先级,它们首先得到解决
float firstValue = (float) (5 / 2); // division of integers
= (float) (2); // 5/2 = 2 , as Integers are being divided
= 2f
float secondValue = (float) 5 / 2; // division of float with integer
= ((float) 5) / 2;
= 5f / 2; // second value is equivalent to this
= 2.5f // as Float divided by Integer is Float
- float firstValue = (float) (5 / 2); // 整数除法
第一步是做5/2 calculation.Then答案在float.If你进一步解释5和2是整数。对两个int数进行int计算后,最后的答案由int返回。这里最终的整数答案 (2) 被转换为浮点数答案。也就是这里使用了wide conversion。所以最后的答案是浮点形式显示的整数值(2)(2.0).
2.float secondValue = (float) 5 / 2; //输出为2.5
由于第一个值(5)被命名为浮点数,所以最终答案是小数本身
以下是我正在使用的表达式:
float firstValue = (float) (5 / 2); //output is 2.0
float secondValue = (float) 5 / 2; //output is 2.5
我被难住了,想不通为什么这种类型转换会返回两个不同的值。我知道我可以做 (5f / 2f)
但我想尝试使用其他类型的表达式进行转换。为什么 firstValue
2.0 而 secondValue
2.5? .5 去哪儿了?
首先是整数数学。这个
float firstValue = (float) (5 / 2);
先用五除以二得二。然后它将 2 转换为 2.0
。第二个是浮点数学。
float secondValue = 5f / 2;
即 2.5(和 float
)。因为 float
除以 int
是 float
.
由于括号具有最高的优先级,它们首先得到解决
float firstValue = (float) (5 / 2); // division of integers
= (float) (2); // 5/2 = 2 , as Integers are being divided
= 2f
float secondValue = (float) 5 / 2; // division of float with integer
= ((float) 5) / 2;
= 5f / 2; // second value is equivalent to this
= 2.5f // as Float divided by Integer is Float
- float firstValue = (float) (5 / 2); // 整数除法
第一步是做5/2 calculation.Then答案在float.If你进一步解释5和2是整数。对两个int数进行int计算后,最后的答案由int返回。这里最终的整数答案 (2) 被转换为浮点数答案。也就是这里使用了wide conversion。所以最后的答案是浮点形式显示的整数值(2)(2.0).
2.float secondValue = (float) 5 / 2; //输出为2.5 由于第一个值(5)被命名为浮点数,所以最终答案是小数本身