C ++ euclidean distance
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;
}
}
Anyone can figure out what the problem might be?
a source to share
It might be better to use hypot()
instead of manual squaring and adding and taking the square root. hypot()
takes care of a number of cases where the naive approach loses precision. It's part of C99 and C ++ 0x, and for compilers that don't have it, it's always boost.math .
a source to share
^
- operator xor
; it does not perform exponentiation.
In general, if you want to raise something, you should use the function std::pow
. However, in this particular case, since it is a square, you are probably better off just using multiplication (e.g. x * x
instead of std::pow(x, 2)
).
a source to share