试图找到两点之间的距离,但我得到了错误的答案:(

Trying to find distance between two points, but I'm getting wrong answers:(

我试图找出两点之间的距离,但结果不对。 如果我输入 (1,2) 和 (4,5) 我得到

距离 = 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);
}

查看main函数内部的变量声明-

int a,b,c,d,D;

数据类型是浮点数而不是整数。

你得到了错误的答案,因为你向函数传递了错误的参数。

D = distance(a,b,c,d);

根据你的输入扫描,你是这样告诉它的:

D = distance(x1,y1,x2,y2);

但是,您的函数采用不同的参数顺序 (x1, x2, y1, y2)。

将该行更改为:

D = distance(a,c,b,d);

你应该会得到正确答案。