【问题标题】:Distance between A, B [closed]A,B之间的距离[关闭]
【发布时间】:2017-04-26 05:16:28
【问题描述】:

我试图计算 2 点 A、B 之间的距离。当我运行终端窗口时,它给了我一个错误的数字。谁能帮我改变一些价值、结构或许多提示。

示例: 在 A : -50 -50 在 B : 50 50 距离为 141.42

#include<stdio.h>
#include<conio.h>
#include<math.h>

typedef struct{
    double a;
    double b;
    double c;
    double d;
}location;

double dist(location  w,location x, location y,location z)
{
    double l;
    l=sqrt(pow((y.c-w.a),2)+pow((z.d-x.b),2));
    return(l);
}

void main()
{
    location h;
    location i;
    location j;
    location k;
    printf("Enter 1st point(A)\n");
    scanf("%lf %lf",&h.a,&i.b);
    printf("Enter 2nd point(B)\n");
    scanf("%1f %1f",&j.c,&k.d);
    double data;
    data = dist(h,i,j,k);
    printf("%.2lf",data);
}

【问题讨论】:

  • 141.42 是这些点之间的正确欧几里得距离。你预计距离是多少?
  • 当您使用%1f格式时,最多会读入一位数字。您似乎打错了小写的L,而是使用了数字1。
  • 真正的问题是为什么这里有 4 个位置(或者为什么位置有 4 个东西)
  • 你预计会发生什么?
  • 欢迎来到 StackOverflow。请收下tour,学习stackoverflow.com/help/how-to-ask。如果您在调试代码方面寻求帮助,请查看 ericlippert.com/2014/03/05/how-to-debug-small-programs

标签: c


【解决方案1】:

你注意到你scanf格式字符串在这两行的区别了吗:

scanf("%lf %lf",&h.a,&i.b);
scanf("%1f %1f",&j.c,&k.d);

没错!第二行使用%1f 而不是%lf。那具有完全不同的含义,在您的情况下是错误的。使用%lf

当您得到不理解的结果时,最好使用调试器,或添加printf 语句来检查您的变量值是否符合您的预期。

【讨论】:

    【解决方案2】:

    通过稻田的更正,代码应该可以工作,但我仍然认为值得一提/纠正较小的错误。

    首先void main()在标准中没有定义。 Why is it bad to type void main() in C++

    如果您使用 GCC,请尝试使用 -Wall 参数进行编译。然后您会收到更多警告,这将帮助您最终编写更好的代码。

    还有,为什么你们有 4 个地点和 4 个成员?我稍微重构了你的代码,我认为这个版本更容易阅读和理解。

    #include <stdio.h>
    #include <math.h>
    
    typedef struct {
        double x;
        double y;
    } Point;
    
    double DistanceBetween(Point p1, Point p2)
    {
        Point vector = {
            p2.x - p1.x, p2.y - p1.y
        };
    
        return hypot(vector.x, vector.y);
    }
    
    int main()
    {
        Point p1;
        Point p2;
    
        printf("Enter first point: ");
        scanf("%lf %lf", &p1.x, &p1.y);
    
        printf("Enter second point: ");
        scanf("%lf %lf", &p2.x, &p2.y);
    
        double distance = DistanceBetween(p1, p2);
        printf("The distance is: %lf\r\n", distance);
    
        return 0;
    }
    

    【讨论】:

    • 可以用标准函数hypot()替换sqrt(pow(vector.x, 2) + pow(vector.y, 2)
    猜你喜欢
    • 2019-04-03
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    相关资源
    最近更新 更多