我想使用 Java 求商和余数,但在涉及重复小数时遇到困难。
以下式为例(用Google计算器测试):
division: 182.5 / (365 / 12) = 6
remainder: 182.5 % (365 / 12) = 0
现在,用 Java 进行一个简单的测试:
System.out.println("division: " + 182.5 / (365.0 / 12));
System.out.println("remainder: " + 182.5 % (365.0 / 12));
输出:
division: 6.000
remainder: 30.415
我知道 double 有局限性,所以我尝试使用 BigDecimal:
BigDecimal daysInYear = new BigDecimal("365");
BigDecimal monthsInYear = new BigDecimal("12");
BigDecimal daysInMonth = daysInYear.divide(monthsInYear, 3, RoundingMode.CEILING);
BigDecimal daysInHalfYear = new BigDecimal("182.5");
BigDecimal division = daysInHalfYear.divide(daysInMonth, 3, RoundingMode.CEILING);
BigDecimal remainder = daysInHalfYear.remainder(daysInMonth);
System.out.println("division: " + division);
System.out.println("remainder: " + remainder);
输出:
division: 6.0
remainder: 30.41666666666666
我需要做什么才能得到以下结果?
182.5 % (365 / 12) = 0
最佳答案
有许多编程语言本身支持有理数的精确运算。 Java 不是其中之一。一般来说,这不是一个大问题,因为 double 的精度对于大多数应用程序来说已经足够了。余数是一种边缘情况,非常小的舍入误差可能会导致大的意外结果。
您的选择是:
- 使用不同的语言
- 使用支持有理数的库(例如 Rational )
- 编写您自己的 Rational 类
- 使用数学重新计算您的运算
x % (y/z) => (x * z % y)/z
关于Java,找到 182.5 % (365/12),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51923528/