我已经编写了一个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.text.DecimalFormat
中的DecimalFormat
类。以下是您需要执行的操作:
- 导入DecimalFormat:
导入java.text.DecimalFormat
- 设置 DecimalFormat 对象:
DecimalFormat df = new DecimalFormat("#.#####");
- 使用该对象来格式化您的号码:
df.format(sumArea(array))
例如,df.format(5.123456)
将返回 5.12346
,因为 5 四舍五入为 6。
关于java - 如何将数学答案四舍五入到小数点后 5 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58582797/