优化代码#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; }
时间: 2024-03-21 10:41:30 浏览: 48
c++所有头文件
5星 · 资源好评率100%
这段代码已经很简洁和高效了,但是可以再做一些微小的优化,比如:
1. 在计算平方的时候使用“乘法”比使用“pow”函数更快:
```
float a = sqrt((A.Getx()-B.Getx())*(A.Getx()-B.Getx()) + (A.Gety()-B.Gety())*(A.Gety()-B.Gety()));
```
2. 在计算三角形面积的时候可以使用海伦公式:
```
float s = (a + b + c) / 2;
return sqrt(s * (s-a) * (s-b) * (s-c));
```
这样可以少计算一个平方根。最终优化后的代码如下:
```
#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((A.Getx()-B.Getx())*(A.Getx()-B.Getx()) + (A.Gety()-B.Gety())*(A.Gety()-B.Gety()));
float b = sqrt((B.Getx()-C.Getx())*(B.Getx()-C.Getx()) + (B.Gety()-C.Gety())*(B.Gety()-C.Gety()));
float c = sqrt((C.Getx()-A.Getx())*(C.Getx()-A.Getx()) + (C.Gety()-A.Gety())*(C.Gety()-A.Gety()));
float s = (a + b + c) / 2;
return sqrt(s * (s-a) * (s-b) * (s-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;
}
```
阅读全文