为什么错误 interface Shape{ void zhouchang(); void mianji(); } class sanjiaoxing implements Shape { double a;double b;double c; sanjiaoxing(double _a,double _b,double _c) { a=_a; b=_b; c=_c; } public void zhouchang() { double d=a+b+c; System.out.println("三角形的周长="+d); } public void mianji() { double area; double s=(a+b+c)/2; area=(int)Math.sqrt(s*(s-a)*(s-b)*(s-c)); System.out.println("三角形的面积="+area); } } class juxing implements Shape{ double e;double f; juxing(double _e,double _f) { e=_e; f=_f; } public void zhouchang() { double g=e+f; System.out.println("矩形的周长="+g); } public void mianji() { double area=e*f; System.out.println("矩形的面积="+area); } } class yuan implements Shape{ double radious; yuan(double _radious){ radious= _radious; } public void zhouchang() { double h=2*3*radious; System.out.println("圆形的周长="+h); } public void mianji() { double area=3*radious*radious; System.out.println("圆形的面积="+area); } } public class Jiekoutest{ public static void main(String[] args) { Shape sanjiaoxing= new sanjiaoxing(3,4,5); Shape jixing= new juxing(6,7); Shape yuan= new yuan(2); sanjiaoxing.zhouchang(); sanjiaoxing.mianji(); juxing.zhouchang(); juxing.mianji(); yuan.zhouchang(); yuan.mianji(); } }
时间: 2023-12-15 21:16:46 浏览: 152
这段代码有两个错误:
1. 在 sanjiaoxing 类的 mianji 方法中,计算三角形面积的公式有误,应该使用海伦公式:
```
double s = (a + b + c) / 2;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
```
2. 在 main 方法中,jixing 变量的类型应该是 juxing,而不是 Shape。
以下是修改后的代码:
```
interface Shape {
void zhouchang();
void mianji();
}
class sanjiaoxing implements Shape {
double a;
double b;
double c;
sanjiaoxing(double _a, double _b, double _c) {
a = _a;
b = _b;
c = _c;
}
public void zhouchang() {
double d = a + b + c;
System.out.println("三角形的周长=" + d);
}
public void mianji() {
double s = (a + b + c) / 2;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
System.out.println("三角形的面积=" + area);
}
}
class juxing implements Shape {
double e;
double f;
juxing(double _e, double _f) {
e = _e;
f = _f;
}
public void zhouchang() {
double g = 2 * (e + f);
System.out.println("矩形的周长=" + g);
}
public void mianji() {
double area = e * f;
System.out.println("矩形的面积=" + area);
}
}
class yuan implements Shape {
double radious;
yuan(double _radious) {
radious = _radious;
}
public void zhouchang() {
double h = 2 * Math.PI * radious;
System.out.println("圆形的周长=" + h);
}
public void mianji() {
double area = Math.PI * radious * radious;
System.out.println("圆形的面积=" + area);
}
}
public class Jiekoutest {
public static void main(String[] args) {
Shape sanjiaoxing = new sanjiaoxing(3, 4, 5);
Shape juxing = new juxing(6, 7);
Shape yuan = new yuan(2);
sanjiaoxing.zhouchang();
sanjiaoxing.mianji();
juxing.zhouchang();
juxing.mianji();
yuan.zhouchang();
yuan.mianji();
}
}
```
注意,这里假设圆形的周长和面积使用的是数学常数 pi 的值,而不是 3。
阅读全文