计算各种图形的周长(多态)
定义接口或类 Shape,定义求周长的方法length()。
定义如下类,实现接口Shape或父类Shape的方法。(1)三角形类Triangle (2)长方形类Rectangle (3)圆形类Circle等。定义测试类ShapeTest,用Shape接口(或类)定义变量shape,用其指向不同类形的对象,输出各种图形的周长。并为其他的Shape接口实现类提供良好的扩展性。
提示: 计算圆周长时PI取3.14。
输入格式:
输入多组数值型数据(double);
一行中若有1个数,表示圆的半径;
一行中若有2个数(中间用空格间隔),表示长方形的长度、宽度。
一行中若有3个数(中间用空格间隔),表示三角形的三边的长度。(需要判断三个边长是否能构成三角形)若输入数据中有0或负数,则不表示任何图形,周长为0。
输出格式:
行数与输入相对应,数值为根据每行输入数据求得的图形的周长。
输入样例:
在这里给出一组输入。例如:
1
2 3
4 5 6
2
-2
-2 -3
输出样例:
在这里给出相应的输出。例如:
6.28
10.00
15.00
12.56
0.00
0.00
python 代码
class Shape:
def __init__(self,x=0,y=0,z=0):
self.x=x;
self.y=y
self.z=z
def length(self):
pass
class Triangle(Shape):
def __init__(self,x,y,z):
super(Triangle,self).__init__(x,y,z)
def length(self):
if(self.x+self.y>self.z and self.z+self.y>self.x and self.z+self.x>self.y):
print("%.2f"%(self.x+self.y+self.z))
else:
print("0.00")
class Rectangle(Shape):
def __init__(self,x,y):
super(Rectangle,self).__init__(x,y)
def length(self):
print("%.2f"%((self.x+self.y)*2))
class Circle(Shape):
def __init__(self,x):
super(Circle,self).__init__(x)
def length(self):
print("%.2f"%(2*self.x*3.14))
while True:
try:
li=[]
li=input().split()
if len(li)==3 :
if (float(li[0]) <= 0 or float(li[1]) <= 0 or float(li[2]) <= 0 ):
print("0.00")
else :
tr=Triangle(float(li[0]),float(li[1]),float(li[2]))
tr.length()
elif len(li) == 2:
if (float(li[0]) <= 0 or float(li[1]) <= 0 ):
print("0.00")
else :
re=Rectangle(float(li[0]),float(li[1]))
re.length()
else :
if(float(li[0]) <= 0):
print("0.00")
else:
ci=Circle(float(li[0]))
ci.length()
except:
break;
java 代码
import java.util.Scanner;
interface Shape
{
double length();
}
class Circle implements Shape
{
double r;
Circle (double r)
{
this.r=r;
if(r<=0) this.r=0;
}
public double length()
{
return 2*3.1415926*r;
}
}
class Rectangle implements Shape
{
double a,b;
Rectangle (double a,double b)
{
this.a=a;
this.b=b;
if(a<=0||b<=0) this.a=this.b=0;
}
public double length()
{
return (a+b)*2;
}
}
class Triangle implements Shape
{
double a,b,c;
Triangle(double a,double b,double c)
{
this.a=a;
this.b=b;
this.c=c;
if(a<=0||b<=0||c<=0) this.a=this.b=this.c=0;
if((a+b<=c)||(a+c<=b)||(b+c<=a)) this.a=this.b=this.c=0;
}
public double length()
{
return a+b+c;
}
}
public class Main
{
public static void main(String[] args)
{
Scanner re=new Scanner(System.in);
double[] l=new double[4];
String s;
while(re.hasNextLine())
{
s=re.nextLine();
String[] st=s.split(" ");
int cnt=0;
for(String x:st)
{
l[cnt++]=Double.parseDouble(x);
}
if(cnt==1)
{
Circle c = new Circle(l[0]);
System.out.printf("%.2f\n",c.length());
}
else if(cnt==2)
{
Rectangle r= new Rectangle(l[0],l[1]);
System.out.printf("%.2f\n",r.length());
}
else if(cnt==3)
{
Triangle t=new Triangle(l[0],l[1],l[2]);
System.out.printf("%.2f\n",t.length());
}
}
}
}