請原諒我的無知,我是一個初學者。DecimalFormat的答案?
誰能告訴我爲什麼我在下面的if/else語句中得到我的錯誤代碼?我認爲我的乘法結果與標準乘法不一樣(有一個.00000000006的差異或類似的東西)。有沒有解決這個問題的方法?我試圖使用DecimalFormat但無濟於事。
如果我添加:
DecimalFormat fmt = new DecimalFormat ("0.###");
到測試儀和
if (fmt.format(z) != fmt.format(result)){
if語句我收到我自己同樣的錯誤陳述。哪裏不對!?
非常感謝。
喬
import java.util.Scanner;
import java.lang.Math;
import java.text.DecimalFormat;
public class Logs {
//integer x field & encapsulation
private static double x;
// x encapsulation
public double getX(){
return x;
}
public void setX (double ex){
if (ex >= 0){
x = ex;
}
else{
System.out.println("You may not choose a negative number, 'x' = 0");
}
}
//integer y field
private static double y;
// y encapsulation
public double getY(){
return y;
}
public void setY (double why){
if (why >= 0){
y = why;
}
else{
System.out.println("You may not choose a negative number, 'y' = 0");
}
}
//tester
public static void main (String [] args){
Logs sample =new Logs();
Scanner var = new Scanner(System.in);
DecimalFormat fmt = new DecimalFormat ("0.###");
sample.setX (var.nextDouble());
sample.setY (var.nextDouble());
x = sample.getX();
y = sample.getY();
double z = (x*y);
double logX = Math.log(y);
double logY = Math.log(x);
double logZ = (logX +logY);
double result = (Math.exp(logZ));
if (z != result){
System.out.printf("%s", "Incorrect answer: be a better coder");
}
else {
System.out.printf("%s %.3d %s %.3d %s %.3d",
"The product of the values you chose is: ", + z,
"\nln(x) + ln(y) is: ", + logZ,
"\nCompute to e: ", + result);
}
}
}
你總是要比較使用'字符串的equals()'。 – jlordo
請參閱http://stackoverflow.com/questions/14749647/why-the-result-of-0-3-3-is-0-89999999999999-in-scala-language例如:) – twillouer
您正在比較字符串與''==。看到http://tinyurl.com/so-java-string-equality –