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\n", 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\n", dist(&p1, &p2)); return 0; }