Using c++ to implement a class of Triangle.
时间: 2024-05-20 18:18:00 浏览: 139
Sure, I can help you with that! Creating a class for Triangle in C is fairly simple. You'll need to define the class with three properties for the three sides of the triangle and some methods to calculate its area and perimeter. Is there anything specific you need help with?
相关问题
using c++ to implement a class of triangle
好的,我可以回答你这个问题。你可以使用以下的代码实现一个三角形类:
```
#include <iostream>
using namespace std;
class Triangle {
private:
int side1, side2, side3;
public:
Triangle(int s1, int s2, int s3) {
side1 = s1;
side2 = s2;
side3 = s3;
}
int getPerimeter() {
return (side1 + side2 + side3);
}
double getArea() {
double s = (side1 + side2 + side3) / 2.0;
return sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
};
int main() {
Triangle t(3, 4, 5);
cout << "Perimeter: " << t.getPerimeter() << endl;
cout << "Area: " << t.getArea() << endl;
return 0;
}
```
这个程序实现了一个三角形类,并且计算了其周长和面积。你可以根据你的需求进行修改。
using c++ to implement a class of trian gle
Sure, to implement a class of triangle using C, you can define a struct for the triangle with three sides as its properties. Then, you can write functions for calculating the perimeter, area or any other operations you need. Here's an example code:
```
#include <stdio.h>
#include <math.h>
struct Triangle {
double side1;
double side2;
double side3;
};
double calculatePerimeter(struct Triangle t) {
return t.side1 + t.side2 + t.side3;
}
double calculateArea(struct Triangle t) {
double p = calculatePerimeter(t) / 2.0;
return sqrt(p * (p - t.side1) * (p - t.side2) * (p - t.side3));
}
int main() {
struct Triangle t1 = { 3.0, 4.0, 5.0 };
printf("Perimeter of triangle t1 = %.2lf\n", calculatePerimeter(t1));
printf("Area of triangle t1 = %.2lf\n", calculateArea(t1));
return 0;
}
```
Please note that this is just an example implementation and there may be other ways to implement a class of triangle in C.
阅读全文