給定 a, b, c,求方程 ax² + bx + c = 0 的實根個數及根值(升序)。a, b, c 為整數,可能為 0。
a == 0:退化為一次方程 bx + c = 0
b == 0:c == 0 → 無限解(輸出 -1),否則無解(0)b != 0:一根 -c/ba != 0:判別式 Δ = b² - 4ac
Δ < 0:無實根(0)Δ == 0:一重根 -b/(2a)Δ > 0:兩根 (-b ± √Δ)/(2a),按大小輸出double 計算,輸出 %.10f(-b-√Δ)/(2a) > (-b+√Δ)/(2a) 則交換(或直接令 √Δ 取負)#include <cstdio>
#include <cmath>
#include <iostream>
using namespace std;
int main() {
long long a, b, c;
while (cin >> a >> b >> c) {
if (a == 0) {
if (b == 0) {
if (c == 0) puts("-1");
else puts("0");
continue;
}
puts("1");
printf("%.10f\n", -double(c)/b);
continue;
}
long long d = b*b - 4*a*c;
if (d < 0) { puts("0"); continue; }
if (d == 0) {
puts("1");
printf("%.10f\n", -double(b)/(2*a));
} else {
puts("2");
double sqrtd = sqrt(double(d));
double x1 = (-b - sqrtd) / (2.0*a);
double x2 = (-b + sqrtd) / (2.0*a);
if (x1 > x2) swap(x1, x2);
printf("%.10f\n%.10f\n", x1, x2);
}
}
return 0;
}
a=0 退化情況long long 防止判別式溢出