创建一个直角三角形类(regular triangle)RTriangle类,实现下列接口IShape。两条直角边长作为RTriangle类的私有成员,类中包含参数为直角边的构造方法。
interface IShape {// 接口
public abstract double getArea(); // 抽象方法 求面积
public abstract double getPerimeter(); // 抽象方法 求周长
}
###直角三角形类的定义:
直角三角形类的构造函数原型如下:
RTriangle(double a, double b);
其中 a 和 b 都是直角三角形的两条直角边。
裁判测试程序样例:
import java.util.Scanner;
import java.text.DecimalFormat;
interface IShape {
public abstract double getArea();
public abstract double getPerimeter();
}
/*你写的代码将嵌入到这里*/
public class Main {
public static void main(String[] args) {
DecimalFormat d = new DecimalFormat("#.####");
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
double b = input.nextDouble();
IShape r = new RTriangle(a, b);
System.out.println(d.format(r.getArea()));
System.out.println(d.format(r.getPerimeter()));
input.close();
}
}
import java.util.Scanner;
import java.text.DecimalFormat;
interface IShape {
public abstract double getArea();
public abstract double getPerimeter();
}
/*你写的代码将嵌入到这里*/
public class Main {
public static void main(String[] args) {
DecimalFormat d = new DecimalFormat("#.####");
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
double b = input.nextDouble();
IShape r = new RTriangle(a, b);
System.out.println(d.format(r.getArea()));
System.out.println(d.format(r.getPerimeter()));
input.close();
}
}
输入样例:
3.1 4.2
输出样例:
6.51
12.5202
正确答案:
class RTriangle implements IShape {
private double a; // 直角边a
private double b; // 直角边b
// 构造函数
public RTriangle(double a, double b) {
this.a = a;
this.b = b;
}
// 计算面积
@Override
public double getArea() {
return 0.5 * a * b;
}
// 计算周长
@Override
public double getPerimeter() {
double c = Math.sqrt(a * a + b * b); // 斜边c
return a + b + c;
}
}