请原谅我的无知,我是初学者。
谁能告诉我为什么我在下面的 if/else 语句中得到错误代码?我认为我的 ln 乘法结果与标准乘法并不完全相同(有 .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);
}
}
}