简体   繁体   English

C ++数组中两点之间的距离

[英]The distance between two points function in array C++

I am having problems understanding what this function is doing, I know its related to finding the distance between two points but I don't see exactly how that is happening... 我在了解此功能的作用时遇到了问题,我知道它与查找两点之间的距离有关,但是我看不到它是如何发生的...

double closestPoints(double points[], int n)
{
double closest = 100.0;

for (int p1 = 0; p1 < n; p1++)
{
    for (int p2 = 0; p2 < n; p2++)
    {
        if (p1 != p2 && abs(points[p1] - points[p2]) < closest)
        {
            closest = abs(points[p1] - points[p2]);
        }
    }
}
return closest;
}

Could someone help me understand it? 有人可以帮我理解吗?

Ok, so with 2 for-statements you just pick all combinations of points (so combine every point with every other). 好的,所以使用2个for语句,您只需选择所有点组合(因此将每个点彼此组合)。

if(p1 != p2) means that if p1 points to the same point as p2 does, you ignore them (because you cannot calculate distance between one point. if(p1 != p2)表示如果p1指向与p2相同的点,则忽略它们(因为无法计算一个点之间的距离。

abs(points[p1] - points[p2]) < closest if distance between 2 chosen points is less than current minimum distance, you set your current minimum distance to this distance. abs(points[p1] - points[p2]) < closest如果两个选定点之间的距离小于当前最小距离,则abs(points[p1] - points[p2]) < closest则将当前最小距离设置为该距离。

ps. ps。 note that abs(points[p1] - points[p2]) is a formula to calculate distance between to points on a line. 请注意, abs(points[p1] - points[p2])是用于计算直线上各点之间距离的公式。

This code is taking an array of doubles and finding which of the points is closest together and recording how close they piston. 此代码采用双打数组,并找出哪些points最接近,并记录它们的活塞距离。 Instead of double closest = 100 you could do double closest = abs(points[0] - points[1]); 除了可以使用double closest = 100还可以使用double closest = abs(points[0] - points[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM