代码之家  ›  专栏  ›  技术社区  ›  beastlyCoder

二次规划的舍入问题

  •  0
  • beastlyCoder  · 技术社区  · 7 年前

    在我练习的一个问题中,目标是写出二次表达式,然后四舍五入到千分之一的位置。以下是所需的输出:

    输出: -0.551,-5.449(顶线答案)

          double a = scan.nextDouble(); 
          double b = scan.nextDouble(); 
          double c = scan.nextDouble(); 
    
          //equation is correct
          double answer1 = 0.001 * Math.floor((-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a)* 1000.0) ;
          double answer2 = 0.001 * Math.floor((-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a) * 1000.0);
    

    我得到的答案是正确的,除了当我开始四舍五入到千分之一位时,有些数字是正确的,而其他的则不是,即使看起来它们是正确的,只是不符合问题。

    我的输出: -1.057,-1.444

    这是不是跟我的修身方式有关?如果您能帮助您理解这个舍入问题,我们将不胜感激:)

    1 回复  |  直到 7 年前
        1
  •  3
  •   markspace    7 年前

    https://floating-point-gui.de/languages/java/

    如何取整

    要获取字符串:

    String.format("%.2f", 1.2399) // returns "1.24"
    String.format("%.3f", 1.2399) // returns "1.240"
    String.format("%.2f", 1.2) // returns "1.20"
    

    要打印到标准输出(或任何打印流):

    System.out.printf("%.2f", 1.2399) // same syntax as String.format()
    

    如果您不想要后面的零:

    new DecimalFormat("0.00").format(1.2)// returns "1.20"
    new DecimalFormat("0.##").format(1.2)// returns "1.2"
    

    如果需要特定的舍入模式:

    new BigDecimal("1.25").setScale(1, RoundingMode.HALF_EVEN); // returns 1.2
    

    如果您确实需要取整实际数字而不仅仅是打印输出:

      double result = Math.round(value * scale) / scale;
    

    哪里 scale 可能固定在 1000 对于三个小数位或计算任意数量的小数位:

      int scale = (int) Math.pow(10, precision);