求方程 \({ax}^2+bx+c=0\)的根,用3個函數分別求當: \(b^2-4ac\)大於0、等於0和小於0時的根並輸出結果。從主函數輸入a,b,c的值
題目解析
根據disc = \(b^2-4ac\) 的值來決定如何求根,題目本身編程不難,不過需要同學們復習一下高中的數學知識哦。
代碼示例
#include<stdio.h>
#include<math.h>
//x1為第一個根,x2為第二個根
float x1, x2, disc, p, q;
void greater_than_zero(float a, float b)
{
float m = sqrt(disc);
x1 = (-b + sqrt(disc)) / (2 * a);
x2 = (-b - sqrt(disc)) / (2 * a);
}
void equal_to_zero(float a, float b)
{
x1 = x2 = (-b) / (2 * a);
}
void smaller_than_zero(float a, float b)
{
p = -b / (2 * a);
q = sqrt(-disc) / (2 * a);
}
int main()
{
int a, b, c;
printf("請輸入 a b c:");
scanf("%d %d %d", &a, &b, &c);
printf("表達式為: %d*x^2+%d*x+%d = 0\n", a, b, c);
disc = b*b - 4 * a*c;
if (disc > 0)
{
greater_than_zero(a, b);
printf("disc>0的根為: x1=%f x2=%f\n", x1, x2);
}
else if (disc == 0)
{
equal_to_zero(a, b);
printf("disc==0的根為:x1=%f x2=%f\n", x1, x2);
}
else
{
smaller_than_zero(a, b);
printf("disc<0的根為:x1=%f+%f x2=%f-%f\n", p, q, p, q);
}
return 0;
}