-5

求助,我希望程序的输出四舍五入到小数点后 2 位.......................... ..................................................... ..................................................... …………………………………………………………………………………………………………………………………………

这是我的代码:

package javaapplication2;
import javax.swing.JOptionPane;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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

int age = 0;             
age = Integer.parseInt(
JOptionPane.showInputDialog(
null, "Enter radius of a circle: "));  

        int radius = 0;
        System.out.println("Enter radius of a circle : ");
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            radius = Integer.parseInt(br.readLine());
        }
        catch(NumberFormatException ne)
        {
            System.out.println("Invalid radius value" );
            System.exit(0);
        }
        catch(IOException ioe)
        {
            System.out.println("IO Error :" + ioe);
            System.exit(0);
        }
        radius = 5;
        double circumference = 2 * Math.PI * radius;
        double area = Math.PI * radius * radius;

        System.out.println("Area of a circle is " + area);
        System.out.println("Perimeter of a circle is " + circumference);

        }
}  
4

2 回答 2

1

由于您只想显示四舍五入的值,而不是将其传递给进一步计算,您可以使用DecimalFormat

DecimalFormat format = new DecimalFormat("0.##");
System.out.println("Area of a circle is " + format.format(area));
System.out.println("Perimeter of a circle is " + format.format(circumference));
于 2012-11-30T02:02:04.550 回答
1

您可以应用以下内容:

public double Round2(double number) {
       return Math.rint(number*100)/100;
}
于 2012-11-30T02:08:56.973 回答