分部是java中的incorect

Zan*_*_x3 0 java floating-point division

我很迷惑.我想要获得一个int价值:

Integer ord = new Double(33 / (-2 * 1.1)).intValue();
Run Code Online (Sandbox Code Playgroud)

期望:-15
输出:-14

怎么了?

当我尝试:

Double d = 33 / (-2 * 1.1);
Run Code Online (Sandbox Code Playgroud)

输出: -14.999999999999998

有任何想法吗?提前致谢!

Tar*_*lah 6

.intValue()将截断frarctinal部分,以便您可以使用Math.ceil(),Math.floor()或者您可以使用Math.round()它近似到最接近的值

Integer result = (int) Math.round(new Double(33/(-2*1.1))); //-15
Integer result = (int) Math.floor(new Double(33/(-2*1.1))); //-15
Integer result = (int) Math.ceil(new Double(33/(-2*1.1)));  //-14
Run Code Online (Sandbox Code Playgroud)

你可以看到Math.ceil()给我们14,因为这是一个负数-14> -15所以-14.9999的ceil是-14,反之则适用于Math.floor()

  • 这取决于Zanas_x3想要什么,但我会说`Math.round()`可能比他希望的更多,而不是`Math.ceil()`. (2认同)