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

标签 c function protocols formula distance

我试图找到两点之间的距离,但结果不正确。 如果我输入 (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);
}

最佳答案

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

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/

相关文章:

json - 如何创建一个将 json 字符串转换为 golang 结构的通用函数?

javascript - 匿名函数与普通函数

具有约束关联类型错误 "Type is not convertible"的 Swift 协议(protocol)

c# - Linux中是否有系统API来提供对文件的原子写操作

c - 重定向标准输入

c# - 按顺序调用多个 API 来检索和传递 token C#

soap - CWMP CPE(客户端)实现

ios - 如何在多个类上调用同一个函数?

c - c和结构中的数组

c++ - 智能感知 : an array may not have elements of this type