用Java计算圆的周长与面积.越简单越好.

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/03 06:06:13
用Java计算圆的周长与面积.越简单越好.

用Java计算圆的周长与面积.越简单越好.
用Java计算圆的周长与面积.越简单越好.

用Java计算圆的周长与面积.越简单越好.
这种最好是写一个抽象类,然后实例化.
public class Test {
public static void main(String[] args) {
Shape circle = new Circle(2);
System.out.println("半径为2的圆的面积为:" + circle.area());
Shape triple = new Triple(3,4,5);
System.out.println("三边长为3,4,5的三角形面积为:"+ triple.area());
Shape rectangle = new Rectangle(5,6);
System.out.println("长宽为5 和6的矩形面积为:"+ rectangle.area());
}
}
abstract class Shape{
public abstract double area();
}
class Circle extends Shape{//圆
private double r;
public Circle(double r){
this.r = r;
}
public double area() {
return Math.PI * Math.pow(r,2);//圆周率*半径的平方
}
}
class Triple extends Shape{//三角形
private double a;
private double b;
private double c;
public Triple(double a,double b,double c){
this.a = a;
this.b = b;
this.c = c;
}
//海伦公式S= √[p(p - a)(p - b)(p - c),p = (a+b+c/2)
public double area() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p-a) *(p - b) *(p-c));
}
}
class Rectangle extends Shape{//矩形
private double width;//宽
private double height;//长
public Rectangle(double width,double height){
this.width = width;
this.height = height;
}
public double area() {
return width * this.height;
}
}
---------------------测试结果
半径为2的圆的面积为:12.566370614359172
三边长为3,4,5的三角形面积为:6.0
长宽为5 和6的矩形面积为:30.0