在寻找两点之间的距离时出现问题


#include <stdio.h>
int main()
{
int x1;
int x2;
int y1;
int y2;
printf("Enter the value of x1 and y1 %d %d ",x1,y1);
scanf("%d %d",&x1,&y1);
printf("Enter the value of x2 and y2 %d %d ",x2,y2);
scanf("%d %d",&x2,&y2);
int l1=x2-x1;
int l2=y2-y1;
int len1=l1*l1;
int len2=l2*l2;
int length=len1+len2;
int lengthf=sqrt(length);
printf("The length between the points = %d",lengthf);

return 0;
}

我没有预料到变量的位置。我必须得到两点之间的距离

代码中有几个错误:

  1. x1,y1,x2,y2未初始化,调用UB

  2. 通过将double转换为int,您将失去实际结果的精度。

  3. 您缺少math.h库。

  4. 您没有检查scanf()

  5. 大量冗余变量


代码可以这样写。点击注释了解。

#include <math.h>
#include <stdio.h>
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
// Storing the coordinate values in a structure.
struct point {
int x;
int y;
};
int main(void)
{
struct point p1 = { 0, 0 };
struct point p2 = { 0, 0 };
fprintf(stdout, "Enter the value of x1 and y1: ");
// Validation of input -- considered good practices.
if (fscanf(stdin, "%d %d", &p1.x, &p1.y) != 2) {
fprintf(stderr, "error: The value(s) are invalid.n");
return EXIT_FAILURE;
}
fprintf(stdout, "Enter the value of x2 and y2: ");
// Validation of input -- considered good practices.
if (fscanf(stdin, "%d %d", &p2.x, &p2.y) != 2) {
fprintf(stderr, "error: The value(s) are invalid.n");
return EXIT_FAILURE;
}
// Finally, evaluation of the distance using pow() and sqrt().
double distance = sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2));
fprintf(stdout, "Distance between two points: %.2lfn", distance);
return EXIT_SUCCESS;
}

最新更新