【问题标题】:DecimalFormat the answer? [duplicate]十进制格式的答案? [复制]
【发布时间】:2013-02-07 17:22:49
【问题描述】:

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

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

    }

  }
}

【问题讨论】:

标签: java decimalformat exp natural-logarithm


【解决方案1】:

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

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

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

详情请见Math.abs(double a)

【讨论】:

  • 我试过这个并收到一个错误:[line: 54] double cannot be dereferenced
【解决方案2】:

建议试试

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

【讨论】:

    【解决方案3】:
    1. 使用 BigDecimal 而不是 double
    2. 使用 StrictMath 代替 Math

    【讨论】:

      【解决方案4】:

      我认为这是因为双重。为了获得最佳实践,请改用 BigDecimal。 请看一下“Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?”。

      【讨论】:

      • 你的意思是 BigDecimal 而不是 BigInteger?
      • 当然,BigDecimal。谢谢指正。
      猜你喜欢
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多