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
", 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
", 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
", dis(&a, &b));
    
    return 0;
}

原文地址:https://www.cnblogs.com/liujiaxin2018/p/14853403.html