c语言中利用结构体计算两点之间的距离。

c语言中利用结构体计算两点之间的距离。

1、

#include <stdio.h>
#include <math.h>  // c语言中基本数学运算的头文件,这里 sqrt函数使用到 

#define sqr(x) ((x) * (x))  // 函数式宏,计算平方 

typedef struct{   //结构体声明, 为类型声明 typedef名 Point,结构体两个结构体成员 x,y 
    double x;
    double y;
}Point;

double dis(Point p1, Point p2)   // 函数返回值double型, 形参为两个结构体类型。 
{
    return sqrt(sqr(p1.x - p2.x) + sqr(p1.y - p2.y));  //计算两点之间的距离, 每一个结构体的成员分别代表各自点的x轴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:  %.3f
", dis(a, b));  //函数调用,实参部分给与两个结构体,a和b。 
    
    return 0;
}

2、

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

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

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

double dist(Point *a, Point *b)
{
    return sqrt(sqr(a -> x - b -> x) + sqr( a -> y - b -> y ));
}

int main(void)
{
    Point p1, p2;
    printf("p1.x = "); scanf("%lf", &p1.x);
    printf("p1.y = "); scanf("%lf", &p1.y);
    
    printf("p2.x = "); scanf("%lf", &p2.x);
    printf("p2.y = "); scanf("%lf", &p2.y);
    
    printf("distanbe result: %.2f
", dist(&p1, &p2));
    
    return 0; 
}

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