[英]Why does my java Code output a wrong number?
我是第一次嘗試 eclipse 並且我正在嘗試使用數字鍵盤對計算器進行編程。 目前我正在編寫逗號函數,但我的代碼不起作用。
這是我的小數位代碼:
System.out.println(first+"");
System.out.println(dec_length(first));
first=((first*Math.pow(10, dec_length(first)))+1) / Math.pow(10, dec_length(first));
textfield.setText(""+format.format(first));
dec_length() 方法是:
public static int dec_length(double input) {
String param=(""+input);
String vergleich =(".0");
String sub= param.substring((param.indexOf('.')));
if (sub.equals(vergleich)) {
return 1;
} else
return sub.length();
}
當我嘗試它時,它適用於前 2 個小數位,但隨后它停止工作。
這是控制台輸出:
5.0
1
5.1
2
5.109999999999999
16
5.109999999999999
16
5.109999999999999
16
有人知道這有什么問題嗎?
問題是您假設所有小數位都可以由 double 類型精確表示。 但事實並非如此。
我建議您將數字存儲為字符串,直到您將其用於計算:
String first = "0";
然后添加一個數字或一個逗號(您當然應該確保您的號碼中只有一個.
):
first += digit; // Add a digit from 0 to 9
first += '.'; // Call this when the comma function is called.
之后,當您想要進行計算部分時,您可以輕松地將字符串解析為雙精度:
double value = Double.parseDouble(first);
我是第一次嘗試蝕,我正在嘗試使用數字鍵盤對計算器進行編程。 目前,我正在對逗號函數進行編程,但是我的代碼無法正常工作。
這是我的小數位數代碼:
System.out.println(first+"");
System.out.println(dec_length(first));
first=((first*Math.pow(10, dec_length(first)))+1) / Math.pow(10, dec_length(first));
textfield.setText(""+format.format(first));
方法dec_length()是:
public static int dec_length(double input) {
String param=(""+input);
String vergleich =(".0");
String sub= param.substring((param.indexOf('.')));
if (sub.equals(vergleich)) {
return 1;
} else
return sub.length();
}
當我嘗試它時,它適用於前2個小數位,但隨后它停止工作。
這是控制台輸出:
5.0
1
5.1
2
5.109999999999999
16
5.109999999999999
16
5.109999999999999
16
有人知道這有什么問題嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.