gpt4 book ai didi

java - 静态方法的十进制格式

转载 作者:行者123 更新时间:2023-12-01 14:24:12 24 4
gpt4 key购买 nike

编辑:这本书有一个拼写错误,用圆柱体和使用的体积代替,但该程序的重​​点是练习使用静态方法,所以这并不重要。

我完成了这个程序并让它工作以获取与我的主类交互的静态方法。我只是遇到了十进制格式的问题。 double 得到小数点后 11 位。我尝试过使用 DecimalFormat,但是无论我把它放在哪里,都没有任何影响。由于现在使用静态方法,我需要做一些额外的事情吗?

import java.text.DecimalFormat; //import DecimalFormat

class Area{

//Area of a Circle
static double Area(double radius){
return Math.PI * (radius * radius);
}

//Area of a Rectangle
static int Area(int width, int length){
return width * length;
}

//Volume of a Cyclinder
static double Area(double radius, double height){
return Math.PI * (radius * radius) * height;
}
}

public class AreaDemo{
public static void main(String[] args){

//Variable Declarations for each shape
double circleRadius = 20.0;
int rectangleLength = 10;
int rectangleWidth = 20;
double cylinderRadius = 10.0;
double cylinderHeight = 15.0;

//Print Statements for the Areas
System.out.println("The area of a circle with a radius of " + circleRadius + " is " + Area.Area(circleRadius)); //Circle
System.out.println("The area of a rectangle with a length of " + rectangleLength + " width of " + rectangleWidth + " is " + Area.Area(rectangleLength, rectangleWidth)); //Rectangle
System.out.println("The area of a cylinder with radius " + cylinderRadius + " and height " + cylinderHeight + " is " + Area.Area(cylinderRadius, cylinderHeight)); //Cylinder
}
}

最佳答案

如果你想使用十进制格式,你可以这样,

double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));

这将打印出 1.23。如果将格式增加为 "#.### 则为 1.235

或更适合您的是

DecimalFormat df = new DecimalFormat("#.##");
//Print Statements for the Areas
System.out.println("The area of a circle with a radius of " + df.format(circleRadius) + " is " + df.format(Area.Area(circleRadius))); //Circle
// do same for your others

关于java - 静态方法的十进制格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17290360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com