The specific example in your question has a several serious errors - among other things you have a syntax error (a parentheses at the wrong place causing the first pow
to only have one parameter) and you're using variables that you never initialized - and then not even printing or returning the result...
With a slight correction, the formula you used is correct:
sqrt(pow((x2-x1), 2) + pow((y2-y1), 2))
As Bathsheba noted, if you want to square a number a faster and more accurate alternative to calling pow() is just to do multiplication:
sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1))
Another alternative is to replace the sqrt
and two multiplications by one math function, hypot
, designed to do exactly what you need:
hypot(x2-x1, y2-y1)
The jury is still out which of the above two options is better. hypot
has the potential of being more accurate and also be able to survive overflows (when the distance squared overflows the floating point limits but the distance itself doesn't), but some report that it is slower than the sqrt-and-multiplication version (see When to use `std::hypot(x,y)` over `std::sqrt(x*x + y*y)`).