C语言 求出平面直角坐标系中两点的距离
生活随笔
收集整理的這篇文章主要介紹了
C语言 求出平面直角坐标系中两点的距离
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include <math.h>
#include <stdio.h>double dist(double x1, double y1, double x2, double y2){return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}int main(void){double x1, y1;double x2, y2;puts("求兩點間的距離。 \n");puts("點A: ");printf("X坐標:");scanf("%lf", &x1);printf("Y坐標:");scanf("%lf", &y1);printf("A (%lf, %lf)\n", x1, y1);puts("點B: ");printf("X坐標:");scanf("%lf", &x2); printf("Y坐標:");scanf("%lf", &y2); printf("B(%lf, %lf)\n", x2, y2);printf("兩點之間的距離d = %f\n", dist(x1, y1, x2, y2));return 0;
}
運行結果:
注:
double sqrt(double x)函數:
計算x的平方根(實參為復數時會發生定義域錯誤)。
使用結構體計算兩點的距離
#include <math.h> #include <stdio.h> #define sqr(n) ((n) * (n))typedef struct{double x;double y; } Point;double distance_of(Point pa, Point pb){return sqrt(sqr(pa.x - pb.x) + sqr(pa.y - pb.y)); }int main(void){Point crnt, dest;printf("當前地點的X坐標:");scanf("%lf", &crnt.x); printf("當前地點的Y坐標:");scanf("%lf", &crnt.y); printf("目的地點的Y坐標:");scanf("%lf", &dest.x); printf("目的地點的Y坐標:");scanf("%lf", &dest.y); printf("到目的地的距離為 %.2f。\n", distance_of(crnt, dest));return 0; }總結
以上是生活随笔為你收集整理的C语言 求出平面直角坐标系中两点的距离的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言 浮点数从0递增至1.0的过程
- 下一篇: C语言 函数式宏的使用