以下简单的浮点算术运算未按预期运行。
double den = (1+j);
System.out.println(den);
den = 1/den;
System.out.println(den);
double newden = 1/(1+j);
System.out.println(newden);
上面的代码给出了以下输出。
7.0
0.14285714285714285
0.0
如上所示,前两个操作按预期工作,但最后一个没有。我想它与变量类型有关但仍然没有弄清楚问题所在。
您能解释一下 Java 中算术运算的行为吗?
如果不涉及 float/double/long
,则 java 中的算术运算在 int
中完成。因此,将其中一个 arg 更改为 float/double,它会按预期工作。
下面的代码可以工作:
double newden = 1d/(i+j);
System.out.println(newden);
来自java spec :
Widening primitive conversion (§5.1.2) is applied to convert either or
both operands as specified by the following rules, in order:
- If either operand is of type double, the other is converted to double.
- Otherwise, if either operand is of type float, the other is converted to float.
- Otherwise, if either operand is of type long, the other is converted to long.
- Otherwise, both operands are converted to type int.