java - 浮点运算未按预期工作

标签 java variables math double

<分区>

以下简单的浮点算术运算未按预期运行。

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.

关于java - 浮点运算未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39896712/

相关文章:

java - 如何摆脱 Maven 快照版本

java - 如何检查方法是否在 Java 中返回 Collection<Foo>?

java - 是否长期保留前导零 SQLITE 插入

bash - 在 bash heredoc 中使用变量

math - 在 Haskell 中实现 Gauss-Jordan 消去法

java - 将映射器更改为 hadoop 2.7.3 中每个工作人员的核心数

java - toString()、==、equals() 对象方法在引用和原始类型上的工作方式有何不同或相似?

javascript - 如何在 Javascript 中从指向它的变量获取对象名称

javascript - 获取 2 矢量3 的 Angular

java - Julia 集算法