나는 네 점이있다. _pointA
_pointB
_pointC
_pointD
. 현재 지점에서 가장 가까운 지점을 찾고 싶습니다. 나는 이와 같은 것을 가졌지 만 때로는 잘못된 결과를줍니다.다른 점에서 가장 가까운 점을 계산하는 가장 좋은 방법은 무엇입니까?
문제 : 내가 근처 pointA
에 당신이 준 점으로 pointC
CGPoint neastPoint=CGPointZero;
for (int i=0; i<3; i++) {
CGFloat x;
CGFloat y;
CGFloat currntDistance;
if (i==0){
x=(pointA.x-currentPoint.x) *(pointA.x-currentPoint.x);
y=(pointA.y-currentPoint.y)*(pointA.y-currentPoint.y);
currntDistance =sqrtf(x+y);
distance=currntDistance;
neastPoint=pointA;
}
else if (i==1){
x=(pointB.x-currentPoint.x) *(pointB.x-currentPoint.x);
y=(pointB.y-currentPoint.y)*(pointB.y-currentPoint.y);
currntDistance =sqrtf(x+y);
if (distance>currntDistance) {
distance=currntDistance;
neastPoint=pointB;
}
}
else if (i==2){
x=(pointC.x-currentPoint.x) *(pointC.x-currentPoint.x);
y=(pointC.y-currentPoint.y)*(pointC.y-currentPoint.y);
currntDistance =sqrtf(x+y);
if (distance>currntDistance) {
distance=currntDistance;
neastPoint=pointC;
}
}
else {
x=(pointD.x-currentPoint.x) *(pointD.x-currentPoint.x);
y=(pointD.y-currentPoint.y)*(pointD.y-currentPoint.y);
currntDistance =sqrtf(x+y);
if (distance>currntDistance) {
distance=currntDistance;
neastPoint=pointD;
}
}
CurrentPoint : {44, 33.140846}
Point A : {71, 178}
Point B : {134, 178}
Point C : {133, 71}
Point D : {75, 67}
Nearast Point : {133, 71}
귀하의 코드는 (당신이'for' 모든'if' 제거 할 수있는 매우 비효율적이다 배열을 사용하면 더 좋을 것입니다.)하지만 작동해야합니다. 정확히 무슨 문제입니까? – Merlevede
if-block body를 공통 함수로 캡슐화하는 것이 좋습니다. 그런 다음 포인트를 목록에 넣고 반복하여 최소 거리의 포인트를 찾습니다. 그것은 아마 비록 작동합니다. –
pointA.y 대신 첫 번째 if 문에서 pointB.y를 사용하고 있습니다. 여기에 오류가 있습니까? 아니면 코드에도 마찬가지입니까? – Logan