AdminBenni - 1 year ago 73

C++ Question

So I have a two dimensional array that holds some value that doesn't matter.

Let's say that the indexes represent x and y positions on a grid and that I have three points on that grid: The main point and two extra points how do I check which extra point is closest to the main point.

This is the code I tried but it didn't seem to quite work.

`if(abs(mainX - extra1X) + abs(mainY - extra1Y) < abs(mainX - extra2X) + abs(mainY - extra2Y))`

{

cout << "Extra point 1 is closer" << endl;

}

else if(abs(mainX - extra1X) + abs(mainY - extra1Y) > abs(mainX - extra2X) + abs(mainY - extra2Y))

{

cout << "Extra point 2 is closer" << endl;

}

else

{

cout << "They are equally close" << endl;

}

All help is greatly appreciated :)

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You are looking for The Distance Formula:

```
double Distance = sqrt(pow((X1 - X2), 2) + pow((Y1 - Y2), 2));
```

Implement and execute that for both points, then check the value of `Distance`

for each point to determine which point is closer.

This should work:

```
double DistanceOne = sqrt(pow((MainX - ExtraXone), 2) + pow((MainY - ExtraYone), 2));
double DistanceTwo = sqrt(pow((MainX - ExtraXtwo), 2) + pow((MainY - ExtraYtwo), 2));
if(DistanceOne < DistanceTwo)
cout << "Point 1 is closer.\n";
else if (DistanceOne > DistanceTwo)
cout << "Point 2 is closer.\n";
else
cout << "Points 1 and 2 are on the same distance from Point Main.\n";
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**