C++优化代码己知三角形的三边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:34:47 浏览: 134
C++求三角形面积
5星 · 资源好评率100%
题目1的代码实现如下:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
float x, y;
public:
Point(float a, float b): x(a), y(b) {}
float Getx() {return x;}
float Gety() {return y;}
};
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(B.Getx() - A.Getx(), 2) + pow(B.Gety() - A.Gety(), 2));
float b = sqrt(pow(C.Getx() - B.Getx(), 2) + pow(C.Gety() - B.Gety(), 2));
float c = sqrt(pow(A.Getx() - C.Getx(), 2) + pow(A.Gety() - C.Gety(), 2));
float p = (a + b + c) / 2;
return sqrt(p * (p - a) * (p - b) * (p - c));
}
};
int main() {
Point A(1, 2);
Point B(3, 4);
Point C(3, 0.5);
Triangle tri(A, B, C);
cout << "Triangle area: " << tri.area() << endl;
return 0;
}
```
题目2的代码实现如下:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
float x, y;
public:
Point(float a, float b): x(a), y(b) {}
float Getx() {return x;}
float Gety() {return y;}
};
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 a = sqrt(pow(B.Getx() - A.Getx(), 2) + pow(B.Gety() - A.Gety(), 2));
float b = sqrt(pow(C.Getx() - B.Getx(), 2) + pow(C.Gety() - B.Gety(), 2));
float c = sqrt(pow(D.Getx() - C.Getx(), 2) + pow(D.Gety() - C.Gety(), 2));
float d = sqrt(pow(A.Getx() - D.Getx(), 2) + pow(A.Gety() - D.Gety(), 2));
float p1 = (a + b + d) / 2;
float p2 = (c + d + b) / 2;
return sqrt(p1 * (p1 - a) * (p1 - b) * (p1 - d) + p2 * (p2 - c) * (p2 - d) * (p2 - b));
}
};
int main() {
Point A(11, 0);
Point B(3, 4);
Point C(5, 2);
Point D(4, 0.5);
Quadrangle quad(A, B, C, D);
cout << "Quadrangle area: " << quad.area() << endl;
return 0;
}
```
阅读全文