首頁  >  文章  >  後端開發  >  計算兩點之間距離的C程序

計算兩點之間距離的C程序

王林
王林轉載
2023-09-09 18:41:151193瀏覽

計算兩點之間距離的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

以上是計算兩點之間距離的C程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除