ax² + bx + c = 0,判別式 Δ = b² - 4ac。
Δ > 0:兩相異實根 x = (-b ± √Δ) / 2a。Δ = 0:兩相同實根 x = -b / 2a。Δ < 0:無實根 (複數根)。#include#include int main() { double a, b, c; printf("請輸入 a b c: "); if (scanf("%lf %lf %lf", &a, &b, &c) != 3) return 1; if (a == 0) { puts("非二次方程"); return 1; } double delta = b*b - 4*a*c; if (delta >= 0) { double sqrt_d = sqrt(delta); double x1 = (-b + sqrt_d) / (2*a); double x2 = (-b - sqrt_d) / (2*a); printf("x1=%.6f\nx2=%.6f\n", x1, x2); } else { puts("原方程無實數解"); // 可選:輸出複數根 // double real = -b/(2*a), imag = sqrt(-delta)/(2*a); // printf("x1=%.2f+%.2fi, x2=%.2f-%.2fi\n", real, imag, real, imag); } return 0; }
%lf 讀取 double,printf 用 %f (或 %lf C99 相容)。sqrt 需 <math.h> 且編譯鏈結 -lm。b 很大時,-b ± √Δ 會發生**災難性抵銷**。double q = -0.5 * (b + (b>0 ? sqrt_d : -sqrt_d)); x1 = q / a; x2 = c / q; // 避免減法抵銷
請輸入 a b c: 2 3 1 x1=-0.500000 x2=-1.000000