gpt4 book ai didi

c++ - 点到线/段的距离

转载 作者:搜寻专家 更新时间:2023-10-31 00:42:19 25 4
gpt4 key购买 nike

我必须计算点到线的距离(检查它是线还是线段)。我不确定 bool 函数 IsSegment 是否正常工作。我可以有一些建议吗?谢谢。

double Distance_From_Line_to_Point(int *a, int *b, int *c, bool IsSegment) {
double distance;
int dot1;
int dot2;
distance = Cross_Product(a, b, c) / Distance(a, b);
if (IsSegment(a,b,c) == true) {
dot1 = Dot_Product(a, b, c);
if (dot1 > 0) {
return Distance(b, c);
}
dot2 = Dot_Product(b, a, c);
if (dot2 > 0) {
return Distance(a, c);
}
}
return fabs(distance);
}

bool IsSegment(int *a, int *b, int *c) {
double angle1;
double angle2;
angle1 = atan(double(b[1] - a[1]) / (b[0] - a[0]));
angle2 = atan(double(c[1] - b[1]) / (c[0] - b[0]));
if ((angle2 - angle1) * (180 / PI) > 90) {
return false;
}
return true;
}

最佳答案

不能直接用公式算距离吗?

所以要找到这条线:

void getLine(double x1, double y1, double x2, double y2, double &a, double &b, double &c)
{
// (x- p1X) / (p2X - p1X) = (y - p1Y) / (p2Y - p1Y)
a = y1 - y2; // Note: this was incorrectly "y2 - y1" in the original answer
b = x2 - x1;
c = x1 * y2 - x2 * y1;
}

http://formule-matematica.tripod.com/distanta-de-dreapta.htm

double dist(double pct1X, double pct1Y, double pct2X, double pct2Y, double pct3X, double pct3Y)
{
double a, b, c;
getLine(pct2X, pct2Y, pct3X, pct3Y, a, b, c);
return abs(a * pct1X + b * pct1Y + c) / sqrt(a * a + b * b);
}

代码使用示例:

#include <CMATH>

void getLine(double x1, double y1, double x2, double y2, double &a, double &b, double &c)
{
// (x- p1X) / (p2X - p1X) = (y - p1Y) / (p2Y - p1Y)
a = y1 - y2; // Note: this was incorrectly "y2 - y1" in the original answer
b = x2 - x1;
c = x1 * y2 - x2 * y1;
}

double dist(double pct1X, double pct1Y, double pct2X, double pct2Y, double pct3X, double pct3Y)
{
double a, b, c;
getLine(pct2X, pct2Y, pct3X, pct3Y, a, b, c);
return abs(a * pct1X + b * pct1Y + c) / sqrt(a * a + b * b);
}


int main(int argc, char* argv[])
{
double d = dist(1,2,3,4,5,6);

return 0;
}

关于c++ - 点到线/段的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12132352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com