#include<iostream> using namespace std; class Triangle {public: Triangle (); void Triangle (float aa ,float bb ,float cc):a(aa),b(bb),c(cc)() float area(); private: float a; float b; float c; }; Triangle::Triangle(float aa,float bb,float cc) { if(a+b>c&&a+c>b&&b+c>a) {aa=a; bb=b; cc=c; } else {aa=0; bb=0; cc=0; cout<<"无法构成三角形"<<endl;} } Triangle::area() {return(a*b*c);} int main() {Triangle Triangle1; cout<<Triangle1.area()<<endl; Triangle box2(3,4,5); cout<<box2.area()<<endl; return 0; }这个程序哪里错了
时间: 2024-03-09 07:48:14 浏览: 47
这个程序有几个错误:
1.在类Triangle中,构造函数的声明和定义不匹配,应该是:
```
Triangle(float aa, float bb, float cc);
```
2.在构造函数中,赋值操作的顺序错误,应该是:
```
a = aa;
b = bb;
c = cc;
```
3.area()函数的返回值应该是一个浮点数,但是实际返回的是a,b,c的乘积,应该是:
```
float area() { float p = (a + b + c) / 2; return sqrt(p * (p - a) * (p - b) * (p - c)); }
```
4.main函数中创建Triangle对象时的参数不匹配,应该是:
```
Triangle Triangle1(0,0,0);
```
修改后的程序如下:
```
#include<iostream>
#include<cmath>
using namespace std;
class Triangle {
public:
Triangle();
Triangle(float aa, float bb, float cc);
float area();
private:
float a;
float b;
float c;
};
Triangle::Triangle(float aa, float bb, float cc) {
if (aa + bb > cc && aa + cc > bb && bb + cc > aa) {
a = aa;
b = bb;
c = cc;
} else {
a = 0;
b = 0;
c = 0;
cout << "无法构成三角形" << endl;
}
}
float Triangle::area() {
float p = (a + b + c) / 2;
return sqrt(p * (p - a) * (p - b) * (p - c));
}
int main() {
Triangle Triangle1(0, 0, 0);
cout << Triangle1.area() << endl;
Triangle box2(3, 4, 5);
cout << box2.area() << endl;
return 0;
}
```
阅读全文