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

