【问题标题】:Division is incorect in java [duplicate]java中的除法不正确[重复]
【发布时间】:2014-01-27 16:20:07
【问题描述】:

我很困惑。我正在尝试获取int 值:

Integer ord = new Double(33 / (-2 * 1.1)).intValue();

预期:-15
输出:-14

怎么了?

当我尝试时:

Double d = 33 / (-2 * 1.1);

输出:-14.999999999999998

有什么想法吗?提前致谢!

【问题讨论】:

  • 已经够近了。欢迎来到浮点运算。如果你想使用 Math.round() 而不是 .intValue()
  • 如果我每次听到这句话都能得到五分钱,我可能会得到 45 美分。
  • 整数序 = Math.round(new Float(33 / (-2 * 1.1)));
  • 这个问题经常被问到。请花些时间,下次再搜索。
  • @pcnThird 如果我每次听到这句话都能得到五分钱,我可能会得到 44.99987 美分。

标签: java floating-point division


【解决方案1】:

intValue() 不进行舍入而是截断。

【讨论】:

    【解决方案2】:

    .intValue() 将截断分形部分,因此您可以使用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
    

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

    【讨论】:

    • 这取决于 Zanas_x3 想要什么,但我想说Math.round() 可能比Math.ceil() 更符合他的期望。
    • 谢谢!我需要截断,因为我期望这样的结果: Integer ord = new Double(32 / (-2 * 1.1)).intValue(); //-14 整数 ord = new Double(33 / (-2 * 1.1)).intValue(); //-15 整数 ord = new Double(34 / (-2 * 1.1)).intValue(); //-15
    【解决方案3】:

    -14.999999999999998 的双精度输出源于双精度类型。浮点数始终是2^n 数字的总和。结果是并非所有数字都可以精确表示,即使使用双精度数也是如此。

    您的整数示例返回 -14,因为 -14.9999999999999998 的整数值为 -14。获取整数值时没有四舍五入。它只是在小数点处被截断。

    对于四舍五入,使用Math.ceil() 向上舍入,Math.floor() 向下舍入或Math.round() 进行一般舍入。

    【讨论】:

      【解决方案4】:

      警告:使用权限参数:P

      Josh Bloch 在他的 Effective Java 书中有一整条内容反对在追求准确性时使用 doublefloat。在我的生活中,例如与货币打交道,我使用BigDecimal获得了最好的结果

      【讨论】:

        【解决方案5】:

        当获取 double 的 int 值时,java 不会为您做任何向上或向下舍入。它只是省略了小数。

        您想要做的是使用 Math.round(double) 来获得您期望的值。

        我相信 Math.round() 的 java 文档说它会返回一个 long 值,但如果你确定你的结果永远不会大于最大 int 值,那么你可以将它转换为一个 int。

         int result = (int) Math.round(new Double(33/(-2*1.1)));
        

        【讨论】:

          【解决方案6】:

          您使用的是 32 位浮点数,因此会损失很多精度。试试Double d = 33 / (-2 * 1.1d); 而且,正如大家所说,舍入比截断好。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-11-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-02-16
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多