0
我遇到浮點問題。雙。例如,Java中的56可能實際上存儲爲.56000 ... 1。浮點錯誤
我想將小數轉換爲分數。我想如何計算機存儲和小數四捨五入來做到這一點使用連分數
,但使用這種方法我的答案是不準確的,由於。
我嘗試另一種方法:
public static Rational rationalize(double a){
if(a>= 1){
//throw some exception
}
String copOut = Double.toString(a);
int counter = 0;
System.out.println(a);
while(a%1 != 0 && counter < copOut.length() - 2){
a *= 10;
counter++;
}
long deno = (long)Math.pow(10,counter);//sets the denominator
Rational frac = new Rational((long)a,deno)//the unsimplified rational number
long gcd = frac.gcd();
long fnum = frac.getNumer();//gets the numerator
long fden = frac.getDenom();//gets the denominator
frac = new Rational(fnum/gcd, fden/gcd);
return frac;
}
我使用的字符串,找到小數的長度來確定我要多少時間乘以10後,我截斷小數。這給我正確的答案,但它不覺得正確的做法? 有人可以建議「正確」的方式來做到這一點?
第一個問題在這裏是* input *是'double.'因此,在任何代碼執行之前,您已經失去了精度。想一想'BigDecimal.' – EJP