【发布时间】: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