为什么两个计算的结果不同?

Wer*_*ook 1 java math

我使用Math.round(...)进行以下两个计算:

double x = 0.57145732;
x = x * 100;
x = Math.round(x * 10);
x = x / 10;
Run Code Online (Sandbox Code Playgroud)

如果我现在打印x的值,它将显示:57.1.

double x = 0.57145732;
x = (Math.round((x * 100) * 10)) / 10;
// x = (Math.round(x * 1000)) / 10; //Also gives me 57.0.
Run Code Online (Sandbox Code Playgroud)

如果我现在打印x的值,它将显示:57.0.

为什么结果会出现这种差异?

pro*_*mer 5

Math.round()方法返回一个int(或long.奥莱VV纠正了我的错误).许多人认为它会回归float或者double会引起混淆.

在第二次计算中,

Math.round((x * 100) * 10)
Run Code Online (Sandbox Code Playgroud)

回报571.现在,这个值和10两者都是整数(571长,10是整数).所以当计算采用表格时

x = 571 / 10
Run Code Online (Sandbox Code Playgroud)

其中x是double,571/10返回57而不是57.1因为它int.然后,57转换为double,它变成了57.0

如果你这样做

x = (double)Math.round((x * 100) * 10) / 10.0;
Run Code Online (Sandbox Code Playgroud)

它的价值变成了57.1.


编辑:该Math.round()功能有两个版本.你使用的那个接受一个double(因为x是double)并返回long.在这种情况下,long和int没有区别.