手工開方(豎式開平方)是經典算術算法,本文還原步驟並對比 C 標準庫 sqrt()、atan2() 計算向量模長與角度。
2 00 . 00 00 ...2,最大平方 ≤2 為 1,商 1,餘 1。00 → 100。除數 = (前商×20) + 試商 × 試商。前商 1 → 除數 (20+x)*x。試 x=4:24*4=96≤100,商添 4,餘 4。00 → 400。前商 14,除數 (280+x)*x。試 x=1:281*1=281≤400,商添 1,餘 119。00 → 11900。前商 141,除數 (2820+x)*x。試 x=4:2824*4=11296≤11900,商添 4。14.14 (保留兩位小數)。核心公式:新除數 = (已得商 * 20 + 試商) * 試商。
#include
#include
#define RAD_TO_DEG (180.0 / (4 * atan(1.0))) // 180/π
int main() {
int x = 10, y = 10;
double magnitude = sqrt(x*x + y*y); // √200 ≈ 14.1421
double angle = RAD_TO_DEG * atan2(y, x); // atan2(y,x) 返回弧度,含象限判斷
printf("Magnitude: %.4f, Angle: %.4f°\n", magnitude, angle);
return 0;
}
Magnitude: 14.1421, Angle: 45.0000°
| 函數 | 頭文件 | 用途 |
|---|---|---|
sqrt(x) | math.h | 平方根,x ≥ 0 |
atan2(y, x) | math.h | 計算 atan(y/x),自動處理象限,返回 [-π, π] |
atan(1) | math.h | π/4,用於編譯期計算 π (4*atan(1)) |
gcc sqrt_demo.c -o sqrt_demo -lm # 需鏈接數學庫 -lm