【问题标题】:How to round a mathematical answer to 5 decimal places [duplicate]如何将数学答案四舍五入到小数点后 5 位 [重复]
【发布时间】:2019-10-27 19:50:00
【问题描述】:

我已经编写了一个 Java 程序,它完全按照它的预期工作,但是,答案需要四舍五入到小数点后 5 位。

我用谷歌搜索了很多,但我看到的每篇文章都有双重输入。这是一个需要四舍五入的 sumArea 答案。

public class COSC_HW13
{
    // Main method
    public static void main(String[] args) 
    {
    // Create an array of four objects
    GeometricObject[] array = {new Circle(5), new Circle(8),
    new Rectangle(3, 4), new Rectangle(4, 2)};

    // Display results
    System.out.println("Total area of elements in array: " 
            + sumArea(array));
    }

    // Returns the sum of the areas of 
    //all the geometric objects in an array
    public static double sumArea(GeometricObject[] a) 
    {
        double sum = 0;
        for (int i = 0; i < a.length; i++) 
        {
            sum += a[i].getArea();

        }
        return sum;
    }

}

【问题讨论】:

    标签: java decimal rounding


    【解决方案1】:

    您可以使用java.text.DecimalFormat 中的DecimalFormat 类。以下是您需要做的:

    1. 导入十进制格式:import java.text.DecimalFormat
    2. 设置 DecimalFormat 对象:DecimalFormat df = new DecimalFormat("#.#####");
    3. 使用对象格式化您的号码:df.format(sumArea(array))

    例如,df.format(5.123456) 将返回 5.12346,因为 5 舍入为 6。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-07
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      • 2015-11-24
      • 2012-03-11
      • 1970-01-01
      相关资源
      最近更新 更多