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

时间:2021-06-06 18:46:18   收藏:0   阅读:0

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;
}

技术图片

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!