In the first part of the question, Java stores .6 as .5999999 (repeats). See this conclusion:
(after first multiply): d=1234.56 (after second multiply): d=12345.599999999999 (after third multiply): d=123455.99999999999
One fix is ββto use d = Math.round (d) right after the loop ends.
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)); } }
It works - try it.
For the second part of your question ...
To call the second constructor from the first, you can use the keyword "this"
this(num, denom)
But it should be the very first line in the constructor ... which makes no sense here (first we need to do some calculations). Therefore, I would not try to do it.
source share