简体   繁体   中英

Translate math formula to C++

I need to write a formula to determine the distance between two points in a plane in C++. ### Here is the formula: 在此处输入图像描述

I wrote such a code for this, but where is my mistake and how should I write the code correctly?:

#include <iostream>
#include <math.h>
using namespace std;

int main()
{
    double x1, x2, y1, y2, distance;
    distance = sqrt((pow(x2-x1), 2) + pow((y2-y1), 2));
    return 0;
}

Under IEEE754 (a floating point standard ubiquitious on desktop personal computers), std::sqrt is required to return the best representable result possible, but std::pow is not.

So

distance = std::sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));

is a better way. Make sure that all the domain variables are initialised prior to the evaluation else the behaviour of the program is undefined.

In order that your program has observable output, write

std::cout << distance;

having supplied appropriate values for x1 , x2 , y1 , and y2 .

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)` ).

I tested this. Below code is working fine

#include <iostream>

#include <math.h>

using namespace std;

double calculateDistance(double x1, double x2, double y1, double y2) {
  return sqrt(pow((x2 - x1), 2) + pow((y2 - y1), 2));
}

int main() {
  double x1 = 5, x2 = 3, y1 = 5, y2 = 4;
  double distance = calculateDistance(x1, x2, y1, y2);
  cout << distance;
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM