方法一:常规计算
#include<stdio.h>
#include<math.h>
void main(){
float a,b,c,d,x1,x2;
printf("请输入a的值:");
scanf("%f",&a);
printf("请输入b的值:");
scanf("%f",&b);
printf("请输入c的值:");
scanf("%f",&c);
d=b*b-4*a*c;
if(d>0){
x1=(-b+sqrt(d))/(2*a);
x2=(-b-sqrt(d))/(2*a);
printf("x1=%g,x2=%g",x1,x2);
}else if(d==0){
x1=x2=-b/(2*a);
printf("x1=x2=%g",x1);
}else{
printf("无解");
}
}
方法二:函数调用,包含共轭复根
#include<stdio.h>
#include<math.h>
float x1,x2,disc,p,q;
void greater_than_zero(float a,float b){
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(){
float a,b,c;
printf("input a,b,c:");
scanf("%f,%f,%f",&a,&b,&c);
printf("equation:%g*x*x+%g*x+%g=0\n",a,b,c);
disc=b*b-4*a*c;
printf("root:\n");
if(disc>0){
greater_than_zero(a,b);
printf("x1=%f\tx2=%f\n",x1,x2);
}else if(disc==0){
equal_to_zero(a,b);
printf("x1=%f\tx2=%f\n",x1,x2);
}else{
smaller_than_zero(a,b);
printf("x1=%f+%f\tx2=%f-%f\n",p,q,p,q);
}
return 0;
}
① 两个不等的实根
② 两个相等的实根
③ 两个共轭复根