c语言学习2026/10/23
一元二次方程求解
题目:求一元二次方程ax2+bx+c=0的解。a,b,c为任意实数。
Input
输入数据有一行,包括a b c的值
$$ ax^2+bx+c=0$$
Output
按以下格式输出方程的根x1和x2。x1和x2之间有一个空格。 $$x_1 \quad x_2$$ (1)如果x1和x2为实根,则以x1>=x2输出。 (2)如果方程是共轭复根,$$x_1=m+ni\quad x_2=m-ni$$ 其中n>0。 其中x1, x2, m,n均保留2位小数。
代码
#include <stdio.h>
#include <math.h>
int main(void) {
double a,b,c;
scanf("%lf%lf%lf",&a,&b,&c);
double x1,x2;
if (a==0) {
x1=-c/b;
x2=-c/b;
printf("%lf %lf",x1,x2);
}
else if (a!=0) {
double t;
t=(pow(b,2)-4*a*c);
if (t>=0) {
x1=(-b+sqrt(t))/(2*a);
x2=(-b-sqrt(t))/(2*a);
if (x1>x2) {
printf("%.2lf %.2lf",x1,x2);
}
else
printf("%.2lf %.2lf",x2,x1);
}
else if (t<0) {
double m=0,n=0;
m=-b/(2.0*a);
n=sqrt(-t)/fabs(2.0*a);
printf("%.2f+%.2fi %.2f-%.2fi\n",m,n,m,n);
}
}
return 0;
}
a=0 的特殊情况
if (a==0) {
x1=-c/b;
x2=-c/b;
printf("%lf %lf",x1,x2);
}
当a!=0时
else if (a!=0) {
double t;
t=(pow(b,2)-4*a*c);
if (t>=0) {
x1=(-b+sqrt(t))/(2*a);
x2=(-b-sqrt(t))/(2*a);
if (x1>x2) {
printf("%.2lf %.2lf",x1,x2);
}
else
printf("%.2lf %.2lf",x2,x1);
}
else if (t<0) {
double m=0,n=0;
m=-b/(2.0*a);
n=sqrt(-t)/fabs(2.0*a);
printf("%.2f+%.2fi %.2f-%.2fi\n",m,n,m,n);
}
}
- 代码
double t ; t=(pow(b,2)-4*a*c)是数学求根公式$$\sqrt {b^2 - 4ac}$$ - 当代码中 t>0 则方程有实数根
- 代码
if (t>=0) {
x1=(-b+sqrt(t))/(2*a);
x2=(-b-sqrt(t))/(2*a);
if (x1>x2) {
printf("%.2lf %.2lf",x1,x2);
}
else
printf("%.2lf %.2lf",x2,x1);
- 当代码 t<0 时方程无实数根,有共轭复数根
- 代码
else if (t<0) {
double m=0,n=0;
m=-b/(2.0*a);
n=sqrt(-t)/fabs(2.0*a);
printf("%.2f+%.2fi %.2f-%.2fi\n",m,n,m,n);
}