內容
求一元二次方程式 ax2+bx+c=0 的根
輸入
輸入三個整數 a, b, c
1 3 -10
1 0 0
1 1 1
輸出
Two different roots x1=?? , x2=??
Two same roots x=??
No real root
PS: 答案均為整數,若有兩個根則大者在前
Two different roots x1=2 , x2=-5
Two same roots x=0
No real root
解題思路
利用
s = b^2 - 4ac
判斷是否有實根,
若有則再判斷兩根
(-b + √s) / 2a
(-b - √s) / 2a
值是否相同
完整程式碼
AC (2ms, 140KB)
#include <stdio.h> #include <math.h>
int a, b, c, s, sr, x1, x2;
int main() { while (scanf("%d %d %d", &a, &b, &c) == 3) { s = (b * b) - (4 * a * c); if (s < 0) { printf("No real root\n"); continue; } sr = sqrt(s); x1 = (-b + sr) / (2 * a); x2 = (-b - sr) / (2 * a); if (sr) { printf("Two different roots x1=%d , x2=%d\n", x1, x2); } else { printf("Two same roots x=%d\n", x1); } } return 0; }
|