题目链接:点击打开链接
计算长方体、四棱锥的表面积和体积
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
计算如下立体图形的表面积和体积。
从图中观察,可抽取其共同属性到父类Rect中:长度:l 宽度:h 高度:z
在父类Rect中,定义求底面周长的方法length( )和底面积的方法area( )。
定义父类Rect的子类立方体类Cubic,计算立方体的表面积和体积。其中表面积area( )重写父类的方法。
定义父类Rect的子类四棱锥类Pyramid,计算四棱锥的表面积和体积。其中表面积area( )重写父类的方法。
输入立体图形的长(l)、宽(h)、高(z)数据,分别输出长方体的表面积、体积、四棱锥的表面积和体积。
Input
输入多行数值型数据(double);
每行三个数值,分别表示l h z
若输入数据中有非正数,则不表示任何图形,表面积和体积均为0。
Output
行数与输入相对应,数值为长方体表面积 长方体体积 四棱锥表面积 四棱锥体积(中间有一个空格作为间隔,数值保留两位小数)
Example Input
1 2 3 0 2 3 -1 2 3 3 4 5
Example Output
22.00 6.00 11.25 2.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 94.00 60.00 49.04 20.00
Hint
四棱锥体公式:V=1/3Sh,S——底面积 h——高
Author
zhouxq
代码实现:
import java.util.Scanner;
class Rectangle {
double length;
double weith;
public Rectangle() {
super();
}
public Rectangle(double length, double weith) {
super();
this.length = length;
this.weith = weith;
}
public double length() {
return 2 * (length + weith);
}
public double area() {
return length * weith;
}
}
class Cubic extends Rectangle {
double heigh;
public Cubic(double a,double b,double heigh) {
super(a,b);
this.heigh = heigh;
}
public double area() {
return length() * heigh + 2 * length * weith;
}
public double tiji() {
Rectangle A = new Rectangle(length,weith);
return A.area() * heigh;
}
}
class Pyramid extends Rectangle {
double heigh;
public Pyramid(double a,double b,double heigh) {
super(a,b);
this.heigh = heigh;
}
public double area() {
double h1 = Math.sqrt(heigh * heigh + 1.0 / 4 * weith * weith);
double h2 = Math.sqrt(heigh * heigh + 1.0 / 4 * length * length);
double s1 = length * h1 / 2;
double s2 = weith * h2 / 2;
return 2 * s1 + 2 * s2 + length * weith;
}
public double tiji() {
Rectangle A = new Rectangle(length,weith);
return A.area() * heigh/3;
}
}
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNext()) {
double len = input.nextDouble();
double wei = input.nextDouble();
double hei = input.nextDouble();
if (len <= 0 || wei <= 0 || hei <= 0) {
len = 0.0;
wei = 0.0;
hei = 0.0;
}
Cubic cubic = new Cubic(len,wei,hei);
Pyramid pyra = new Pyramid(len,wei,hei);
System.out.printf("%.2f %.2f %.2f %.2f\n",cubic.area(),cubic.tiji(),pyra.area(),pyra.tiji());
}
}
}