英文:
Why is it possible for an int and a float to operate together in Java?
问题
public static void main(String[] args) {
float result = (int)Math.floor(1.5F);
System.out.println(result);
所以这是我放入Java的内容
但我想知道的是...
应该是:
float result = (float)Math.floor(1.5F); 吗?
因为结果是在寻找一个float,但是(int)Math.floor(1.5F)会产生一个int
或者至少是我这个新手大脑所思考的 :/
英文:
public static void main(String[] args) {
float result = (int)Math.floor(1.5F);
System.out.println(result);
so this is what I plugged into java
but what I'm wondering is...
shouldn't it be:
float result = (float)Math.floor(1.5F); ?
because the result is looking for a float but (int)Math.floor(1.5F) produces an int
or atleast thats what my noob brain is thinking :/
答案1
得分: 3
这是Java中的宽化原始类型转换的示例。有关更多信息,请参阅官方Java规范(滚动到5.1.2. 宽化原始类型转换
和相关的5.1.3. 收窄原始类型转换
部分)。
具体在你的情况下,你正在看到:
将int或long值进行宽化转换为float,或将long值进行宽化转换为double,可能会导致精度丢失 - 也就是说,结果可能会丢失一些值的最不显著位。在这种情况下,得到的浮点值将是整数值的正确舍入版本,使用IEEE 754最近舍入模式(§4.2.4)。
英文:
This is an example of Widening Primitive Conversion in Java. See the official Java spec for more information (scroll down to 5.1.2. Widening Primitive Conversion
and the related 5.1.3. Narrowing Primitive Conversion
).
Specifically in your case, you're seeing:
> A widening conversion of an int or a long value to float, or of a long
> value to double, may result in loss of precision - that is, the result
> may lose some of the least significant bits of the value. In this
> case, the resulting floating-point value will be a correctly rounded
> version of the integer value, using IEEE 754 round-to-nearest mode
> (§4.2.4).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论