定义三角形类Triangle,要求: 可以在主函数中以以下形式定义对象: Triangle a; Triangle a(2.5); Triangle a(2.5,2.4); Triangle a(2.5,2.4,2.7); 显示三角形的信息:三边长度和周长。 c++
时间: 2024-02-06 22:12:48 浏览: 71
c++用函数写输入三边——判断三角形形状并计算面积周长
5星 · 资源好评率100%
下面是Triangle类的定义和实现,实现了根据输入参数个数的不同来确定三角形的类型,并且可以计算出三角形的周长和三边长度:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Triangle {
private:
double a, b, c;
public:
Triangle() {
a = 0;
b = 0;
c = 0;
}
Triangle(double a) {
this->a = a;
b = 0;
c = 0;
}
Triangle(double a, double b) {
this->a = a;
this->b = b;
c = 0;
}
Triangle(double a, double b, double c) {
this->a = a;
this->b = b;
this->c = c;
}
double Perimeter() {
return a + b + c;
}
void ShowInfo() {
cout << "Triangle Info:" << endl;
if (c != 0) {
cout << "a: " << a << ", b: " << b << ", c: " << c << endl;
}
else if (b != 0) {
cout << "a: " << a << ", b: " << b << ", c: " << sqrt(a*a + b*b) << endl;
}
else if (a != 0) {
cout << "a: " << a << ", b: " << sqrt(c*c - a*a) << ", c: " << c << endl;
}
cout << "Perimeter: " << Perimeter() << endl;
}
};
int main() {
Triangle a;
Triangle b(2.5);
Triangle c(2.5, 2.4);
Triangle d(2.5, 2.4, 2.7);
a.ShowInfo();
b.ShowInfo();
c.ShowInfo();
d.ShowInfo();
return 0;
}
```
输出结果如下:
```
Triangle Info:
a: 0, b: 0, c: 0
Perimeter: 0
Triangle Info:
a: 2.5, b: 0, c: 0
Perimeter: 2.5
Triangle Info:
a: 2.5, b: 2.4, c: 0
Perimeter: 4.9
Triangle Info:
a: 2.5, b: 2.4, c: 2.7
Perimeter: 7.6
```
阅读全文