interface Math
{
double PI=3.1415926;
}class Arithmetic implements Math
{
double roundArea(double radius)
{
return PI*radius*radius;
}
}class Student
{
public static void main(String[] args)
{
Arithmetic a=new Arithmetic();
System.out.println( a.roundArea(3));
//要把上行结果作四舍五入,并保留二位小数,应如何操作?
System.out.println(Math.PI);
System.out.println(Arithmetic.PI);
System.out.println(a.PI);
}
}

解决方案 »

  1.   

    可以用JAVA中提供的小数格式化命令
    import java.text.DecimalFormat; DecimalFormat a = new DecimalFormat("0.00");//0.00代表保留两位小数 然后调用a.format()
    就可以了
      

  2.   

    interface MyMath
    {
    double PI=3.1415926;
    }class Arithmetic implements MyMath
    {
    double roundArea(double radius)
    {
    return PI*radius*radius;
    }
    }public class Student
    {
    public static void main(String[] args)
    {
    Arithmetic a=new Arithmetic();
    System.out.println( a.roundArea(3));
    //以下简单实现了保留两位小数 和C语言是一样的:)
    System.out.printf("%.2f\n", a.roundArea(3));
    System.out.println(Math.PI);
    System.out.println(Arithmetic.PI);
    System.out.println(a.PI);
    }
    }
    建议把Math改名,因为存在java.lang.Math类
      

  3.   

    各位网友:
       您好!感谢你们的提示,但javac Student.java 时出现如下信息:能否再帮我看一下:   
     cannot resolve symbol
    symbol  : method printf (java.lang.String,double)
    location: class java.io.PrintStream
    System.out.printf("%.2f\n", a.roundArea(3)).println();