描述:
思想:这里主要是分为三步来进行求解
1.计算出每一条直线的表达式
2.计算线段两两之间的交点
3.根据三个交点利用公式来计算出面积
代码:
#include <bits/stdc++.h>
using namespace std;
// 求出直线两两之间的交点,然后使用公式
// (x1,y1)、(x2,y2)、(x3,y3)
// s = 1/2|x1(y1-y2) + x2(y2-y3) + x3(y3-y1)|
// 计算两条直线的交点
pair<double, double> intersection(double A1, double B1, double C1, double A2, double B2, double C2) {
double det = A1 * B2 - A2 * B1;
if (det == 0) {
throw runtime_error("Lines are parallel");
}
double x = (B1 * C2 - B2 * C1) / det;
double y = (A2 * C1 - A1 * C2) / det;
return {x, y};
}
// 计算三角形面积
double triangleArea(double x1, double y1, double x2, double y2, double x3, double y3) {
return 0.5 * fabs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));
}
int main() {
// 输入点坐标
double x11, y11, x12, y12;
double x21, y21, x22, y22;
double x31, y31, x32, y32;
cin >> x11 >> y11;
cin >> x12 >> y12;
cin >> x21 >> y21;
cin >> x22 >> y22;
cin >> x31 >> y31;
cin >> x32 >> y32;
// 求直线方程系数 Ax+By+C = 0;/* */
double A1 = y12 - y11, B1 = x11 - x12, C1 = x12 * y11 - x11 * y12;
double A2 = y22 - y21, B2 = x21 - x22, C2 = x22 * y21 - x21 * y22;
double A3 = y32 - y31, B3 = x31 - x32, C3 = x32 * y31 - x31 * y32;
// 求三条直线的交点
pair<double, double> p1 = intersection(A1, B1, C1, A2, B2, C2);
pair<double, double> p2 = intersection(A2, B2, C2, A3, B3, C3);
pair<double, double> p3 = intersection(A3, B3, C3, A1, B1, C1);
// 计算三角形面积
double area = triangleArea(p1.first, p1.second, p2.first, p2.second, p3.first, p3.second);
// 输出面积
cout << fixed << setprecision(6) << area << endl;
return 0;
}