目录
c++ 一个点a ,一条折线(n个点)b,求折线b上 与a x相同时 y方向的差异
c++ 一个点a ,一条折线(n个点)b,求折线b上 与a x相同时 y方向的差异
#include <iostream>
#include <vector>
#include <cmath>
#include <limits>
struct Point {
double x, y;
};
double calculateYDifferenceToPolyline(const std::vector<Point>& polyline, const Point& a) {
double minDifference = std::numeric_limits<double>::infinity();
for (size_t i = 0; i < polyline.size() - 1; ++i) {
const Point& P1 = polyline[i];
const Point& P2 = polyline[i + 1];
// 检查点 a 是否在 P1 和 P2 之间的 x 范围内
if ((a.x >= P1.x && a.x <= P2.x) || (a.x >= P2.x && a.x <= P1.x)) {
// 计算 a 在 P1 -> P2 线段上的对应 y 坐标
double yLine = P1.y + (P2.y - P1.y) * (a.x - P1.x) / (P2.x - P1.x);
// 计算 y 方向上的差异
double difference = a.y - yLine;
// 更新最小差异
minDifference = std::min(minDifference, std::abs(difference));
}
}
return minDifference;
}
int main() {
// 定义折线
std::vector<Point> polyline = {
{1.0, 1.0}, {2.0, 3.0}, {3.0, 3.0}, {4.0, 5.0}, {5.0, 5.0}, {6.0, 7.0}
};
// 定义需要判断的点
Point a = { 3.5, 3.5 };
// 计算 a 与折线段的 y 方向差异
double difference = calculateYDifferenceToPolyline(polyline, a);
std::cout << "dis: " << difference << " units." << std::endl;
return 0;
}
判断点是否在折线下方:
#include <iostream>
#include <vector>
struct Point {
double x, y;
};
int checkPointRelativeToPolyline(const std::vector<Point>& polyline, const Point& P3) {
int isBelow = 0;
for (size_t i = 0; i < polyline.size() - 1; ++i) {
const Point& P1 = polyline[i];
const Point& P2 = polyline[i + 1];
// 计算向量叉积
double crossProduct = (P2.x - P1.x) * (P3.y - P1.y) - (P2.y - P1.y) * (P3.x - P1.x);
if (crossProduct < 0) {
isBelow = 1;
}
}
return isBelow;
}
int main() {
// 定义折线
std::vector<Point> polyline = {
{1.0, 1.0}, {2.0, 3.0}, {3.0, 3.0}, {4.0, 5.0}, {5.0, 5.0}, {6.0, 7.0}
};
// 定义需要判断的点
Point P3 = { 3.5, 4.0 };
// 检查 P3 相对于折线的每个线段的位置
checkPointRelativeToPolyline(polyline, P3);
return 0;
}