1.11M Members

Hi,
I am trying to calculate the distance between two points, by using Pythagorean Theorem and the x,y coordinates of two points. However, I have the following issue in line 14: "Expression must have integral or enum type".

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

int main ()
{
float a, b, c, d, distance;

{
cout << "Input x1 and y1 ";
cin >> a >> b;
cout << "Input x2 and y2 ";
cin >> c >> d;
distance = sqrt((c-a)^2+(d-b)^2);
cout << "The distance between the two points : "<< distance;
}
return 0;
}
``````

Are you sure you're using the right operator here:

``````distance = sqrt((c-a)^2+(d-b)^2)
``````

Wouldn't it just be better to do:

``````float distance2 = (a*a) + (c * c); // square
distance = sqrt(distance2); // find the square root
cout << "The distance between the two points : "<< distance;

20, 20

40, 30

= 31.6228
``````

Seems right?

Yeah, the problem is that ^ is not the exponent operator in c++. Rather a^b performs the bit xor operator on the two operands. As the bit xor operator requires two integer types to work (or even to make decent sense) it makes no sense to have it work on floats. Instead you have to find another way to implement exponents. (phorce gave the simplest solution to the ^2 problem, ie `a*a`)

Thanks for the quick replies. Phorce, my calculation could be wrong, but distance = 44.72 when values of 20, 20 and 40, 30 are used.

31.6, 44.7, both wrong.

Rikkie, your code, once corrected, gives the correct response of 22.36, which is 1/2 what you show above. What did you do?

One other point:
For C++, the math library is <cmath>, not <math.h>

I worte this program a while ago it uses functions however, it should give you the correct algorithm you are looking for:

``````#include <iostream>
#include <cmath>

using namespace std;

double Distance(int x1, int y1, int x2, int y2)
{
return sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
}

int main(int argc, char *argv[]) {

int coord[2*2] = {20, 20,
40, 30};

cout << Distance(coord[0], coord[1], coord[2], coord[3]) << endl;

}
``````

@vmanes is right, the algorithm I gave was wrong (in the first instance) so apologies for this.

You
This article has been dead for over six months: Start a new discussion instead
Post:
View similar articles that have also been tagged: