float 精度、sqrt 替代實作square(representation_sign) 傳的是函數指標,非返回值;loop_until(square, a, b) 同理。representation_sign 返回 float(判別式),主程式未存入變數直接丟失。loop_until(float sum, float b, float a) 宣告與調用 loop_until(square, a, b) 參數位置對不上。absouluteValue 拼寫錯誤(應為 absoluteValue),且函數原型宣告在函數內部(舊式 K&R 風格),現代 C 應前置宣告。math.h 卻用數學運算,雖手寫牛頓法開根號但精度/效率不如 sqrt。main 缺少返回型別,應為 int main(void)。#include
#include
// 前置宣告
float absoluteValue(float x);
float newtonSqrt(float x); // 牛頓法開根號
float discriminant(float a, float b, float c); // 判別式 b^2 - 4ac
void printRoots(float sqrtD, float a, float b); // 印根
// 牛頓法開根號(教學用,實務用 sqrtf)
float newtonSqrt(float x) {
if (x < 0) return -1; // 調用者已檢查判別式
const float eps = 1e-6f;
float guess = x > 1 ? x : 1.0f;
while (absoluteValue(guess * guess - x) >= eps)
guess = 0.5f * (guess + x / guess);
return guess;
}
float absoluteValue(float x) {
return x < 0 ? -x : x;
}
float discriminant(float a, float b, float c) {
float d = b * b - 4 * a * c;
if (d < 0) {
printf("判別式 < 0,無實根(複數根)\n");
return -1; // 調用者檢查負值
}
return d;
}
void printRoots(float sqrtD, float a, float b) {
float x1 = (-b + sqrtD) / (2 * a);
float x2 = (-b - sqrtD) / (2 * a);
printf("根 1 = %.6f\n根 2 = %.6f\n", x1, x2);
}
int main(void) {
float a, b, c;
printf("請依序輸入 a, b, c (ax^2 + bx + c = 0): ");
if (scanf("%f %f %f", &a, &b, &c) != 3) return 1;
if (a == 0) { printf("a 不能為 0(非二次方程)\n"); return 1; }
float D = discriminant(a, b, c);
if (D < 0) return 0;
float sqrtD = newtonSqrt(D); // 或 sqrtf(D) 需 #include 並連結 -lm
printRoots(sqrtD, a, b);
return 0;
}
| 問題 | 修正 |
|---|---|
| 函數返回值丟失 | 主程式用變數接收:float D = discriminant(...); |
| 函數指標誤當返回值傳遞 | 傳遞 float 數值:printRoots(sqrtD, a, b); |
| 參數順序混亂 | 統一順序 (a, b, c) 或 (sqrtD, a, b),宣告/定義/調用三處一致 |
| 拼寫錯誤 | absoluteValue 正確拼寫 |
| 缺少標頭檔 | 若用 sqrtf 需 #include <math.h> 並編譯加 -lm |
main 型別 | int main(void) + return 0; |
C 語言**表達式求值後若不存入變數,結果即銷毀**。discriminant(a,b,c) 算出判別式,若不寫 float D = ...,下一行根本拿不到這個值。這是**值語意**的基本規則,非語法限制。
sqrtf#include
// 編譯: gcc -std=c11 -Wall -Wextra -o quad quad.c -lm
float sqrtD = sqrtf(D); // 單精度,比雙精度 sqrt 快且精度足夠
教學階段手寫牛頓法理解迭代原理,**實務專案直接用 sqrtf**。