黑马程序员技术交流社区

标题: 一个练习题中的代码。Math.PI 和 用 final 定义的PI有什么区别 [打印本页]

作者: 小泉真也    时间: 2013-12-30 13:45
标题: 一个练习题中的代码。Math.PI 和 用 final 定义的PI有什么区别
  1. //【利用程序,构造一个 半径=5 和半径=1 的圆的对象,并显示两个圆的半径 和 面积】
  2. //再将第二个对象的半径改为100,显示新的半径和面积。

  3. public class TestCirclel
  4. {
  5.         class Criclel
  6.         {
  7.                 double radius;
  8.                 Circlel()
  9.                 {
  10.                         radius = 1.0;
  11.                 }
  12.                
  13.                 Circlel(double newRadius)
  14.                 {
  15.                         radius = (newRadius);
  16.                 }

  17.                 double getArea()
  18.                 {
  19.                         return radius * radius * Math.PI;
  20.                 }
  21.                        
  22.         }
  23.        
  24.        
  25.         public static void main(String[] args)
  26.         {
  27.                 Circlel myCriclel = new Circlel(5.0);
  28.                 System.out.println("The area of the circlel of radius " +
  29.                                                         myCirclel.radius + " is" + myCriclel.getArea());
  30.                
  31.                 Criclel yourCirclel = new Circlel();
  32.                 System.out.println("The area of the circlel of radius " +
  33.                                                         yourCirclel.radius + " is" + yourCriclel.getArea());
  34.                
  35.                 yourCriclel.radius = 100;
  36.                 System.out.println("The area of the circlel of radius " +
  37.                                                         yourCirclel.radius + " is" + yourCriclel.getArea());
  38.                                                        
  39.         }
  40. }
复制代码
【Q1】Math.PI 和 用 final 定义的PI有什么区别?
【Q2】这里Math 是什么意思呢?
【Q3】可不可以用已经学过的  final PI替换?

作者: 布鲁Go    时间: 2013-12-30 14:49
【Q1】Math.PI 和 用 final 定义的PI有什么区别?
答:Math.PI  是固定的,是属于Math类中的一个属性,一定是3.141592653589793 (也即比任何其他值都更接近 e(即自然对数的底数)的 double 值。)而final 定义的PI就不一定是这个值了,可能就定义为3.14。只是说你自己顶一个值,让他成为常量,方便阅读。

【Q2】这里Math 是什么意思呢?
是java中的一个类。。java.lang.Math   .属于自动导入的一个类。就是等于被人给你写好了一个东西,方便让你调用。
Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。

【Q3】可不可以用已经学过的  final PI替换?
当然那可以,只不过没那么精准而已。。因为你不会定义到小数点那么后面。
作者: 浮出一个美    时间: 2013-12-30 22:18
Math是一个类,PI是Math里的一个静态常量,ctrl+点击鼠标左键看源码,你就懂了:
/**
     * The <code>double</code> value that is closer than any other to
     * <i>pi</i>, the ratio of the circumference of a circle to its
     * diameter.
     */
    public static final double PI = 3.14159265358979323846;

看完懂了吧,你要自己定义还是用别人帮你已经定义好的,看你需求了。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2