我有一个点(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/