您好,欢迎来到华拓科技网。
搜索
您的当前位置:首页pta-java-6-2 创建一个直角三角形类实现IShape接口

pta-java-6-2 创建一个直角三角形类实现IShape接口

来源:华拓科技网

创建一个直角三角形类(regular triangle)RTriangle类,实现下列接口IShape。两条直角边长作为RTriangle类的私有成员,类中包含参数为直角边的构造方法。

interface IShape {// 接口

public abstract double getArea(); // 抽象方法 求面积

public abstract double getPerimeter(); // 抽象方法 求周长

}

###直角三角形类的定义:

直角三角形类的构造函数原型如下:
RTriangle(double a, double b);

其中 ab 都是直角三角形的两条直角边。

裁判测试程序样例:


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;
    }
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo6.cn 版权所有 赣ICP备2024042791号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务