简体   繁体   English

浮点数二进制促销

[英]Binary Numeric Promotion for Floats

In the JLS in 5.6.2. 在5.6.2中的JLS中。 Binary Numeric Promotion: 二进制数值促销:

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order: 当运算符将二进制数字提升应用于一对操作数时,每个操作数必须表示一个可转换为数字类型的值,以下规则适用:

If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8). 如果任何操作数是引用类型,则将其进行拆箱转换(第5.1.8节)。

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules: 扩展原语转换(第5.1.2节)适用于转换以下规则指定的一个或两个操作数:

If either operand is of type double, the other is converted to double. 如果一个操作数的类型为double,则另一个将转换为double。

Otherwise, if either operand is of type float, the other is converted to float. 否则, 如果其中一个操作数的类型为float,则另一个将转换为float。

Otherwise, if either operand is of type long, the other is converted to long. 否则,如果其中一个操作数的类型为long,则另一个将转换为long。

Otherwise, both operands are converted to type int. 否则,两个操作数都将转换为int类型。

This confuses me because both http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/mixed.html and https://alvinalexander.com/java/java-int-double-float-mixed-type-division-arithmetic-rules 这让我感到困惑,因为http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/mixed.htmlhttps://alvinalexander.com/java/java-int-double-float-混合类型分算术规则

state that 指出

All floating point values (float and double) in an arithmetic operation (+, −, *, /) are converted to double type before the arithmetic operation in performed. 在执行算术运算之前,算术运算(+,-,*,/)中的所有浮点值(浮点和双精度)都将转换为双精度类型。

With my understanding, according to the JLS, adding 1 float and 1 integer would result in a float. 根据我的理解,根据JLS,将1浮点数和1整数相加将导致浮点数。 However, according to the other sources, adding 1 float and 1 integer would result in a double? 但是,根据其他消息来源,将1 float和1 integer相加将导致double?

When a source makes a claim contrary to the JLS, chances are good that it's wrong. 当消息来源提出违背JLS的主张时,很可能错了。 In this case, the following demonstrates the behaviour that the JLS describes: 在这种情况下,以下内容演示了JLS描述的行为:

    Number n = 1 + 0.1f;
    System.out.println(n instanceof Float); // true
    System.out.println(n instanceof Double); // false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM