判断两点是否在直线的同侧C++代码
时间: 2024-09-15 19:04:21 浏览: 33
判断两直线是否相交 C++ MFC
5星 · 资源好评率100%
在C++中判断两点A(x1, y1)和B(x2, y2)是否位于直线l的同侧,通常需要考虑三点共线的情况,因为如果点在线上,也视为在同一侧。直线l可以用两个点P(x0, y0)和Q(x0', y0')来代表,斜率为(m = (y0 - y0') / (x0 - x0')),截距(b = y0 - m * x0)。对于任意一点R(x, y),我们有公式判断其在直线上方、下方还是两侧:
1. 如果m * (x - x0) + b > y - y0,点R在直线下方;
2. 如果m * (x - x0) + b < y - y0,点R在直线上方;
3. 否则,点R在直线上。
下面是C++代码实现:
```cpp
#include <cmath>
bool arePointsOnSameSide(double x1, double y1, double x2, double y2,
double x0, double y0, double x0p, double y0p) {
double slope = (y0p - y0) / (x0p - x0);
double intercept = y0 - slope * x0;
// 点在同一直线上的特殊情况处理
if (std::abs(slope) == std::numeric_limits<double>::infinity()) {
return (x1 == x0 && y1 <= y0) || (x2 == x0 && y2 >= y0);
}
double m1 = slope * (x1 - x0) + intercept;
double m2 = slope * (x2 - x0p) + intercept > y1 - y0p && m2 * (x2 - x0p) + intercept > y2 - y0p);
}
// 使用示例
int main() {
double x1 = 0, y1 = 0, x2 = 5, y2 = 4, x0 = 1, y0 = 2, x0p = 3, y0p = 2;
bool sameSide = arePointsOnSameSide(x1, y1, x2, y2, x0, y0, x0p, y0p);
if (sameSide) {
std::cout << "Points A and B are on the same side of the line." << std::endl;
} else {
std::cout << "Points A and B are on different sides of the line." << std::endl;
}
return 0;
}
```
阅读全文