优化代码己知三角形的三边a,b,c,求面积的公式为: p= (a+b+s)/2. S=sqrt(p(p-a)(p-b)(b-c)) class Point private: float x,y public: Point(float a, float b ): x(a)y(b)() ; float Getx() (return x;} float Gety()(retun y;)· 题目 1:class trianglel. private Point A,B,C; public float area(); 求任意三角形 ABC 的面积,其中A(1,2),B(B,3),(3,0.5) 题目 2: class quadrangle{ private Point A, B,C D; public float area(); } 求任意四边形ABCD的面型的面积,其中A(11),B(3,4)C(5,2)D(4, 0.5)
时间: 2024-04-03 13:35:09 浏览: 84
用三边求三角形面积
题目1:
```
#include <cmath>
class Triangle {
private:
Point A, B, C;
public:
Triangle(Point a, Point b, Point c) : A(a), B(b), C(c) {}
float area() {
float a = sqrt(pow(A.Getx()-B.Getx(), 2) + pow(A.Gety()-B.Gety(), 2));
float b = sqrt(pow(B.Getx()-C.Getx(), 2) + pow(B.Gety()-C.Gety(), 2));
float c = sqrt(pow(C.Getx()-A.Getx(), 2) + pow(C.Gety()-A.Gety(), 2));
float p = (a + b + c) / 2;
return sqrt(p * (p-a) * (p-b) * (p-c));
}
};
int main() {
Point A(1, 2), B(3, 4), C(3, 0.5);
Triangle t(A, B, C);
float area = t.area();
return 0;
}
```
题目2:
```
#include <cmath>
class Quadrangle {
private:
Point A, B, C, D;
public:
Quadrangle(Point a, Point b, Point c, Point d) : A(a), B(b), C(c), D(d) {}
float area() {
float ab = sqrt(pow(A.Getx()-B.Getx(), 2) + pow(A.Gety()-B.Gety(), 2));
float bc = sqrt(pow(B.Getx()-C.Getx(), 2) + pow(B.Gety()-C.Gety(), 2));
float cd = sqrt(pow(C.Getx()-D.Getx(), 2) + pow(C.Gety()-D.Gety(), 2));
float da = sqrt(pow(D.Getx()-A.Getx(), 2) + pow(D.Gety()-A.Gety(), 2));
float ac = sqrt(pow(A.Getx()-C.Getx(), 2) + pow(A.Gety()-C.Gety(), 2));
float p1 = (ab + bc + ac) / 2;
float p2 = (cd + da + ac) / 2;
float s1 = sqrt(p1 * (p1-ab) * (p1-bc) * (p1-ac));
float s2 = sqrt(p2 * (p2-cd) * (p2-da) * (p2-ac));
return s1 + s2;
}
};
int main() {
Point A(11, 0), B(3, 4), C(5, 2), D(4, 0.5);
Quadrangle q(A, B, C, D);
float area = q.area();
return 0;
}
```
阅读全文