C 程式用於計算兩點之間的距離


給定兩點的座標,任務是找出兩點之間的距離並顯示結果。

在二維平面上有兩個點,用 A 和 B 表示,其各自座標為 (x1, y1) 和 (x2, y2);要計算它們之間的距離,有一個直接公式,如下所示

$$\sqrt{\lgroup x2-x1\rgroup^{2}+\lgroup y2-y1\rgroup^{2}}$$

以下是表示兩個點及其差的示意圖

$$\frac{(x_2-x_1)}{(x_1,y_1)\:\:\:\:\:\:(y_2-y_1)\:\:\:\:\:\:(x_2,y_2)}$$

下面使用的方法如下

  • 輸入座標,如 x1、x2、y1 和 y2
  • 應用此公式來計算兩點之間的差
  • 列印距離

演算法

Start
Step 1-> declare function to calculate distance between two point
   void three_dis(float x1, float y1, float x2, float y2)
      set float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) * 1.0)
      print dis
step 2-> In main()
   Set float x1 = 4
   Set float y1 = 9
   Set float x2 = 5
   Set float y2 = 10
   Call two_dis(x1, y1, x2, y2)
Stop

示例

#include <stdio.h>
#include<math.h>
//function to find distance bewteen 2 points
void two_dis(float x1, float y1, float x2, float y2) {
   float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) * 1.0);
   printf("Distance between 2 points are : %f", dis);
   return;
}
int main() {
   float x1 = 4;
   float y1 = 9;
   float x2 = 5;
   float y2 = 10;
   two_dis(x1, y1, x2, y2);
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出

Distance between 2 points are : 1.414214

更新於: 18-10-2019

3K+瀏覽

開始您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.