微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c语言中用结构体表示点的坐标,并计算两点之间的距离

c语言中用结构体表示点的坐标,并计算两点之间的距离

1、

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

#define sqr(x) ((x) * (x))

typedef struct{
    double x;
    double y;
}Point;

double dist(Point p1, Point p2)  //此处没有使用结构体对象的指针作为形参,是因为不需要对传入的结构体的成员进行修改 
{
    return sqrt(sqr(p1.x - p2.x) + sqr(p1.y - p2.y));
}

int main(void)
{
    Point a, b;
    printf("a - x:  "); scanf("%lf", &a.x);
    printf("a - y:  "); scanf("%lf", &a.y);
    printf("b - x:  "); scanf("%lf", &b.x);
    printf("b - y:  "); scanf("%lf", &b.y);
    
    printf("distance between a and b:  %.2f\n", dist(a, b));
    
    return 0;
}

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

#define sqr(x) ((x) * (x))

typedef struct{
    double x;
    double y;
}Point;

double dis(Point *p1, Point *p2)
{
    return sqrt(sqr((*p1).x - (*p2).x) + sqr((*p1).y - (*p2).y));    
} 

int main(void)
{
    Point a, b;
    
    printf("a - x:  "); scanf("%lf", &a.x);
    printf("a - y:  "); scanf("%lf", &a.y);
    printf("b - x:  "); scanf("%lf", &b.x);
    printf("b - y:  "); scanf("%lf", &b.y);
    
    printf("distanbe between a and b: %.2f\n", dis(&a, &b));
    
    return 0;
}

 

 ↓

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

#define sqr(x) ((x) * (x))

typedef struct{
    double x;
    double y;
}Point;

double dis(Point *p1, Point *p2)
{
    return sqrt(sqr(p1 -> x - p2 -> x) + sqr(p1 -> y - p2 -> y));    
} 

int main(void)
{
    Point a, b;
    
    printf("a - x:  "); scanf("%lf", &a.x);
    printf("a - y:  "); scanf("%lf", &a.y);
    printf("b - x:  "); scanf("%lf", &b.x);
    printf("b - y:  "); scanf("%lf", &b.y);
    
    printf("distanbe between a and b: %.2f\n", dis(&a, &b));
    
    return 0;
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐