C程序计算点与线之间的距离

标签 c line distance point

我有一个点(x1, y1)和一条线y = m.x + q。而且,我的任务是找到给定点和线之间的最短距离。

下面是我的 C 代码。

有人可以帮助我修改我的代码吗,因为它给了我一些错误(错误的答案)

#include "punto_retta.h"
#include <math.h>
#include <stdio.h>

double x1,y1,m,q,distance;

int main () {

    printf ("Enter the coefficient 'm' of the line: \n");
    scanf ("%lf", &m);
    printf ("Enter the coefficient 'q' of the line: \n");
    scanf ("%lf", &q);
    printf ("Enter the value of x1: \n");
    scanf ("%lf", &x1);
    printf ("Enter the value of y1: \n");
    scanf ("%lf", &y1);

    distance = (fabs (y1 - (m * x1 - q))) / (sqrt (1 + m * m));

    printf ("The distance is %.3f \n", distance);
}

最佳答案

我猜您在计算点 (x1, y1) 和直线 y = m.x + q 之间的距离公式时犯了错误。

替换:

distance = (fabs (y1 - (m * x1 - q))) / (sqrt (1 + m * m));

与:

distance = (fabs (y1 - m * x1 - q)) / (sqrt (1 + m * m));

编辑:查看您不断收到编译错误的原因是因为 y1 已在 math.h< 中声明 头文件。而且,我想如果我没记错的话,你一定是使用 C++ 编译器来编译你的代码。

... Rest of the upper code of math.h header file
_CRTIMP double __cdecl j0 (double);
_CRTIMP double __cdecl j1 (double);
_CRTIMP double __cdecl jn (int, double);
_CRTIMP double __cdecl y0 (double);
_CRTIMP double __cdecl y1 (double);     // y1 is declared here
_CRTIMP double __cdecl yn (int, double);

_CRTIMP double __cdecl chgsign (double);

... Rest Code

要做:将变量 y1 的名称更改为 C 程序文件中的其他名称。

关于C程序计算点与线之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34185224/

相关文章:

c - 指针在内存中的作用域

检查点是否属于正方形

android - distanceTo 返回的距离是多少?

mysql - 这个 MySQL 经纬度距离函数的错误是什么?

c - printf 的格式化

c++ - 我该怎么做才能让我的代码寻找最少数量的硬币?

C语言。阶乘代码(尽可能短)

python - 如何从python中的gzip压缩文件中获取随机行而不将其读入内存

python - 一些 Tkinter create_line 命令不绘制垂直线,但其他命令却绘制垂直线

Matlab:如何在图像中弯曲线条