Reputation: 67
I am trying to find distance between two points, but the result is off. If i type in (1,2) and (4,5) I get
Distance = 1.414214
instead of 4.242640
This happens regardless of what numbers I input.
#include<stdio.h>
#include<math.h>
float distance(float a, float b, float c, float d);
int main()
{
float a,b,c,d,D;
printf("Please enter the first x coordinate. x1= ");
scanf("%f",&a);
printf("Please enter the first x coordinate. y1= ");
scanf("%f",&b);
printf("Please enter the first x coordinate. x2= ");
scanf("%f",&c);
printf("Please enter the first x coordinate. y2= ");
scanf("%f",&d);
D = distance(a,b,c,d);
printf("Distance = %f",D);
return 0;
}
float distance(float x1, float x2, float y1, float y2)
{
float d, D, x, y, X, Y;
x = x1 - x2;
y = y1 - y2;
X = x*x;
Y = y*y;
d = X + Y;
float sqrtf (float d);
return sqrtf(d);
}
Upvotes: 0
Views: 127
Reputation: 2921
You're getting the wrong answer because you're passing the wrong arguments to your function.
D = distance(a,b,c,d);
Based on your input scanning, you are telling it this:
D = distance(x1,y1,x2,y2);
However, your function takes a different order of arguments (x1, x2, y1, y2
).
Change that line to this:
D = distance(a,c,b,d);
And you should get the right answer.
Upvotes: 1
Reputation: 8279
Look at the variable declaration inside the main function-
int a,b,c,d,D;
The data type be a float instead of integer.
Upvotes: 0