C语言:1028.自定义函数求一元二次方程
题目描述:
求方程 的根,用三个函数分别求当b^2-4ac大于0、等于0、和小于0时的根,并输出结果。从主函数输入a、b、c的值。
题解:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(int argc,char *argv[])
{
float gen1(float a,float b,float c);
float gen2(float a,float b,float c);
float gen3(float a,float b,float c);
float a,b,c,d;
scanf("%f %f %f", &a, &b, &c);
d = b*b - 4*a*c;
if(d > 0){
gen1(a,b,c);
}else if(d == 0){
gen2(a,b,c);
}else{
gen3(a,b,c);
}
return 0;
}
float gen1(float a,float b,float c){
float x1, x2, d;
d = b*b - 4*a*c;
x1 = -b / (2*a) + sqrt(d) / (2*a);
x2 = -b / (2*a) - sqrt(d) / (2*a);
printf("x1=%.3f x2=%.3f", x1, x2);
}
float gen2(float a,float b,float c){
float x1,x2,d;
d = b*b - 4*a*c;
x1 = -b / (2*a);
x2 = -b / (2*a);
printf("x1=%.3f x2=%.3f",x1,x2);
}
float gen3(float a,float b,float c){
float x1,x2,d;
d = 4*a*c - b*b;
x1 = -b / (2*a);
x2 = -b / (2*a);
printf("x1=%.3f+%.3fi x2=%.3f-%.3fi", x1, sqrt(d)/(2*a), x2, sqrt(d)/(2*a));
}