給定平面直角坐標系中兩點 A(x1, y1)、B(x2, y2),求兩點之間的歐幾里得距離。公式為:
distance = √((x2-x1)² + (y2-y1)²)
distance() 函式,接受四個整數參數,返回 float 距離。main() 中提示輸入兩點座標,調用函式並格式化輸出。abs() 計算座標差絕對值(其實直接相減平方結果相同,保留可讀性)。math.h 使用 sqrt(),編譯時需鏈接數學庫(gcc -lm)。#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// 使用結構體封裝點座標,提升語義清晰度
typedef struct { int x, y; } Point;
float distance(Point a, Point b) {
int dx = a.x - b.x;
int dy = a.y - b.y;
return sqrt(dx*dx + dy*dy); // 直接平方,無需 abs()
}
int main() {
Point p1, p2;
printf("Enter first point (x y): ");
if (scanf("%d %d", &p1.x, &p1.y) != 2) return 1;
printf("Enter second point (x y): ");
if (scanf("%d %d", &p2.x, &p2.y) != 2) return 1;
printf("Distance: %.4f\n", distance(p1, p2));
return 0;
}
double 型別支援更大範圍與精度。z 或動態陣列。sqrt 直接比較平方和。int,建議轉 long long 或 double 運算。#include <math.h> 或編譯未加 -lm 導致連結錯誤。scanf 格式字串缺少空格換行,導致輸入緩衝區殘留字元影響後續讀取。