This code compiles and runs but does not output the correct distances.
for (int z = 0; z < spaces_x; z++)
{
double dist=( ( (spaces[z][0]-x)^2) + ( (spaces[z][1]-y)^2) );
dist = abs(dist);
dist = sqrt(dist);
cout << "for x " << spaces[z][0] <<
" for y " << spaces[z][1] <<
" dist is "<< dist << endl;
if (dist < min_dist)
{
min_dist = dist;
index = z;
}
}
Does anyone have an idea what the problem could be?
The syntax ^ 2
does not mean raise to the power of 2 - it means XOR. Use x * x
.
double dx = spaces[z][0] - x;
double dy = spaces[z][1] - y;
double dist2 = dx * dx + dy * dy;
It may be a better idea to use hypot()
instead of manually squaring and adding and taking a the square root. hypot()
takes care of a number of cases where naive approach would lose precision. It is a part of C99 and C++0x, and for the compilers that don't have it, there's always boost.math.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With