1

请原谅我的无知,我是初学者。

谁能告诉我为什么我在下面的 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);

    }

  }
}
4

4 回答 4

1

您正在比较字符串引用而不是它们的,并且您想要String.equals()例如z.equals(result)

但是,我认为您要做的是将两个十进制数字与一定的精度进行比较。计算差异并确定它是否在可接受的误差范围内更直观,例如

if (Math.abs(z - result) < 0.01) {
   // ok
}

有关详细信息,请参阅Math.abs(double a)

于 2013-02-07T17:26:01.193 回答
0

我建议尝试

if (!fmt.format(z).equals(fmt.format(result))) {

于 2013-02-07T17:26:23.563 回答
0

我认为这是因为双重。为了获得最佳实践,请改用 BigDecimal。请看一下“为什么我看到一个双变量初始化为某个值,例如 21.4 as 21.399999618530273? ”。

于 2013-02-07T17:26:38.813 回答
0
  1. 使用 BigDecimal 而不是 double
  2. 使用 StrictMath 而不是 Math
于 2013-02-07T17:32:17.377 回答