x3_2 图形面积计算 (1/10 不知道为什么)

我们有一些图形的边长数据,这些图形包括三角新和矩形,请你编写一个程序求出它们的面积。
请你实现一个基础图形类Graph,然后实现三角形类Triangle和矩形类Rectangle,继承自Graph。根据输入的边数实现不同的对象,并计算面积。
输入格式:
一行,一个整数n,表示图形个数。
n行,每行是用空格隔开的整数。
输出格式:
n行,每行是一个图形的面积。
输入样例:
2
5 5
6 6 6
输出样例:
25
15

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        String stemp = in.nextLine();
        int[] ans = new int[1000];
        int cnt = 0;

        for(int i = 0; i < n; i++) {
            String str = in.nextLine();
            String[] s = str.split(" ");
            if(s.length == 2) {
                int a = Integer.parseInt(s[0]);
                int b = Integer.parseInt(s[1]);
                Rectangle r = new Rectangle(a, b);
                ans[cnt++] = r.getArea();
            }else {
                int a = Integer.parseInt(s[0]);
                int b = Integer.parseInt(s[1]);
                int c = Integer.parseInt(s[2]);
                Triangle t = new Triangle(a, b, c);
                ans[cnt++] = t.getArea();
            }
        }

        for(int i = 0; i < cnt; i++) {
            System.out.println(ans[i]);
        }

        in.close();
    }

}

abstract class Graph{
    int a, b, c;
    abstract int getArea();
    void print() {
        System.out.println(this.getArea());
    }
}

class Triangle extends Graph{
    Triangle(int a, int b, int c){
        this.a = a;
        this.b = b;
        this.c = c;
    }
    int getArea() {
        int l = (a + b + c) / 2;
        return (int) Math.sqrt(l * (l - a) * (l - b) * (l - c));
    }
}

class Rectangle extends Graph{
    Rectangle(int a, int b){
        this.a = a;
        this.b = b;
    }
    int getArea() {
        return a * b;
    }
}
/*
4
5 5
6 6 6
4 4 4
3 4

 */

猜你喜欢

转载自blog.csdn.net/qq_31474267/article/details/81051933