对于问题的第一部分,Java将.6存储为.5999999(重复)。看到以下输出:
(after first multiply): d=1234.56(after second multiply): d=12345.599999999999(after third multiply): d=123455.99999999999
一种解决方法是在循环结束后立即使用d = Math.round(d)。
public class Rational { private int num, denom; public Rational(double d) { String s = String.valueOf(d); int digitsDec = s.length() - 1 - s.indexOf('.'); int denom = 1; for(int i = 0; i < digitsDec; i++){ d *= 10; denom *= 10; } int num = (int) Math.round(d); this.num = num; this.denom = denom; } public Rational(int num, int denom) { this.num = num; this.denom = denom; } public String toString() { return String.valueOf(num) + "/" + String.valueOf(denom); } public static void main(String[] args) { System.out.println(new Rational(123.456)); }}它有效-试试吧。
对于您问题的第二部分…
为了从第一个调用第二个构造函数,可以使用“ this”关键字
this(num, denom)
但这必须是构造函数中的第一行…在这里没有意义(我们必须先进行一些计算)。因此,我不会尝试这样做。



