【问题标题】:3 / 2: Division paradox (Java)3 / 2:除法悖论(Java)
【发布时间】:2020-02-28 05:11:14
【问题描述】:

我刚写了这个,我找不到它不能按预期解决除法的原因。有人可以解释一下这里发生了什么吗?

代码如下:

/*
3/2
 */
package paradoja;

public class Paradoja {

    public static void main(String[] args) {
        float dividendo, divisor, resto, cociente;

        dividendo = 3;
        divisor = 2;
        resto = dividendo % divisor;
        cociente = dividendo / divisor;

        System.out.printf("--------DIVISION--------\n");
        System.out.printf("El propósito es dividir 3 entre 2 y, a continuación, hacer la prueba.\n------------------------\n");
        System.out.printf("Dividendo = %.2f\nDivisor = %.2f\nCociente = %.2f\nResto = %.2f\n", dividendo, divisor, cociente, resto);
        System.out.printf("--------PRUEBA--------\n");
        System.out.printf("%.2f * %.2f + %.2f = %.2f (¿?)\n----------------------\n", cociente, divisor, resto, cociente * divisor + resto);
    }

}

这只是一个 3/2 的除法和进一步的测试。它返回 4 而不是 3。感谢您的宝贵时间!

【问题讨论】:

  • “悖论”是什么意思?你能解释一下代码在做什么吗?您可能会将floats 与整数进行比较,或者将苹果与橙子进行比较。
  • 计算是使用二进制数完成的,据我记得,0.5 没有有限表示
  • @Einek 是的,它是十进制(你刚刚写的)和二进制。
  • 正确的返回是 4 no 3,如果你在测试中看到计算结果是 '1.50 * 2.00 + 1.00' = 4.0

标签: java division paradox


【解决方案1】:

我已经在程序中的每个点注释了你的变量值。

package paradoja;

public class Paradoja {

    public static void main(String[] args) {
        float dividendo, divisor, resto, cociente;

        dividendo = 3;
        divisor = 2;
        resto = dividendo % divisor;     // resto = 3.0 % 2.0 = 1.0
        cociente = dividendo / divisor;  // cociente = 3.0 / 2.0 = 1.5

        System.out.printf("--------DIVISION--------\n");
        System.out.printf("El propósito es dividir 3 entre 2 y, a continuación, hacer la prueba.\n------------------------\n");
        System.out.printf("Dividendo = %.2f\nDivisor = %.2f\nCociente = %.2f\nResto = %.2f\n", dividendo, divisor, cociente, resto);
        System.out.printf("--------PRUEBA--------\n");
        // The last parameter passed to the System.out.printf() statement is cociente * divisor + resto = 1.5 * 2.0 + 1.0 = 4.0
        System.out.printf("%.2f * %.2f + %.2f = %.2f (¿?)\n----------------------\n", cociente, divisor, resto, cociente * divisor + resto);
    }

}

【讨论】:

    【解决方案2】:

    好的。 resto = 整数除法的余数 - 3 % 2 = 1。

    但你不是在做整数除法。你正在做浮点除法。所以你最后的计算是:

    cociente * divisor + resto
    1.5 * 2 + 1 = 4
    

    如果您将所有这些都存储在整数而不是浮点数中,它将按照您的预期进行。或者,如果您在最终计算中转换为整数,它会按您期望的方式工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多