求解答为啥部分正确?逻辑上代码好像也没什么问题呀,编译和运行都过了的
主要是测试点2也不清楚测试的数据是什么,看了半天代码没看出来问题在哪,计算面积的公式也没错呀
7-1 抽象基类Shape派生3个类
声明抽象基类Shape,由它派生出三个类,圆形Circle,矩形Rectangle,三角形Triangle,用一个函数输出三个面积。
输入格式:
在一行中依次输入5个数,圆的半径,长方形的高和宽,三角形的高和底,中间用空格分隔
输出格式:
圆的面积,长方形的面积,三角形的面积,小数点后保留2位有效数字,每个面积占一行。
输入样例:
在这里给出一组输入。例如:
3 3 4 3 4
输出样例:
在这里给出相应的输出。例如:
28.27
12.00
6.00
我的代码:
package 抽象基类Shape派生3个类;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] a = new int[5];
for(int i=0;i<a.length;i++) {
a[i]=in.nextInt();
}
Shape c = new Circle(a[0]);
Shape r = new Rectangle(a[1],a[2]);
Shape t = new Triangle(a[3],a[4]);
System.out.printf("%.2f\n%.2f\n%.2f",c.area(),r.area(),t.area());
}
}
abstract class Shape{
abstract double area();
}
class Circle extends Shape{
private double radius;
public Circle(double r) {
this.radius=r;
}
public double area() {
return Math.PI*radius*radius;
}
}
class Rectangle extends Shape{
private double height,length;
public Rectangle(double h, double l) {
this.height=h;
this.length=l;
}
public double area() {
return height*length;
}
}
class Triangle extends Shape{
private double height,length;
public Triangle(double h, double l) {
this.height=h;
this.length=l;
}
public double area() {
return (height*length)/2;
}
}
运行结果
你的代码假设了输入都是 int ,测试数据有没有可能是浮点数?