我试图找到两点之间的距离,但结果不正确。 如果我输入 (1,2) 和 (4,5) 我得到 p>
距离 = 1.414214
而不是 4.242640
无论我输入什么数字,都会发生这种情况。
#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);
}
最佳答案
您得到了错误的答案,因为您向函数传递了错误的参数。
D = distance(a,b,c,d);
根据您的输入扫描,您告诉它:
D = distance(x1,y1,x2,y2);
但是,您的函数采用不同顺序的参数(x1, x2, y1, y2
)。
将该行更改为:
D = distance(a,c,b,d);
你应该得到正确的答案。
关于c - 试图找到两点之间的距离,但我得到了错误的答案 :(,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28598165/