abstract class Shape
{
abstract float Area();
abstract void printArea();
}
class Rectangle extends Shape
{
int width;
int length;
public Rectangle(int newWidth,int newLength)
{
width=newWidth;
length=newLength;
}
public float Area()
{
return width*length;
}
public void printArea()
{
System.out.println("矩形的面积是:"+width*length);
}
}
class Circle extends Shape
{
final float pi=3.14F;
int radius;
public Circle(int newRadius)
{
radius=newRadius;
}
public float Area()
{
return pi*radius*radius;
}
public void printArea()
{
System.out.println("圆形的面积是:"+pi*radius*radius);
}
}
class ChouXiang
{
public static void main(String[] args)
{
Rectangle s1=new Rectangle(3,4);
Circle s2=new Circle(2);
s1.printArea();
s2.printArea();
//System.out.println("Hello World!");
}
}
为什么矩形的返回值是整型而不是单精度,怎么解决。。。。
先行谢过。
System.out.println("矩形的面积是:"+width*length); 直接拿两个整型乘结果还是整型的啊
在这调用你的Area方法
public void printArea()
{
System.out.println("矩形的面积是:"+width*length);
}
长和宽都是 int相乘怎么会是float
因为你定义的 width 和length都是int型的,所以返回值还是int型,而你计算圆的面积 半径与float类型的数据相乘所以得到的就是float类型
单精度 也就是float类型,而你定义的矩形的宽和高都为int类型(整数型),两个整数型相乘结果还是整数型,
你直接把矩形的宽和高改为float类型就可以了
你圆形返回的是单精度,是因为你的pi*radius*radius 中 pi是单精度的,结果转化为单精度了
你用float类型相乘再将结果转成float类型
int 类型的 他怎么返回单精度呢
矩形的返回类型 虽然是float 但是是二个int类型相称没有精度 所以是整形
Java中数字类型有两种,整形和浮点型,其中浮点型又由单精度浮点数和多精度浮点数。三种类型存在一种逐渐扩展的关系:
int->float->double对于不同的数字类型进行混合运算,运算后生成结果为最宽类型
知道了,解决方法如下:
public float Area()
{
return (float)(width*length);
}
public void printArea()
{
System.out.println("矩形的面积是:"+Area());
}