#include <stdio.h>
#include <math.h>
int cal(double a,double b,double c){
double delta,x[2],m,n,i,j;
if (fabs(a) <= 1e-6){
if (fabs(b) <= 1e-6)
puts("Not an equation");
else
printf("%.2lf",-c/b);
}
else{
delta=b*b - 4*a*c;
m = -b / (2*a);
n = sqrt(fabs(delta)) / (2*fabs(a));
i = m + n;
j = m - n;
if (delta < 0)
printf("%.2lf+%.2lfi %.2lf-%.2lfi",m,n,m,n);
else {
if (i == j)
printf("%.2lf %.2lf",i,i);
else {
x[0] = (i > j) ? i : j;
x[1] = (i > j) ? j : i;
printf("%.2lf %.2lf \n", x[0], x[1]);
}
}
}
printf("\n");
if(a==0&&b==0&&c==0)
return 0;
else if(a==0&&b==0&&c!=0)
return 1;
else if(a==0&&b==0)
return 2;
else if(b*b-4*a*c>=0)
return 3;
else
return 4;
}
int main()
{
double a,b,c;
scanf("%lf%lf%lf",&a,&b,&c);
printf("%d",cal(a,b,c));
return 0;
}
具体的代码实现和讲解如下,望采纳
#include <stdio.h>
#include <math.h>
int quadratic_roots(double a, double b, double c, double roots[2]) {
if (a == 0 && b == 0 && c == 0) {
return 0;
} else if (a == 0 && b == 0) {
return 1;
} else if (a == 0) {
roots[0] = -c / b;
return 2;
} else {
double discriminant = b * b - 4 * a * c;
if (discriminant >= 0) {
roots[0] = (-b + sqrt(discriminant)) / (2 * a);
roots[1] = (-b - sqrt(discriminant)) / (2 * a);
return 3;
} else {
return 4;
}
}
}
int main() {
double roots[2];
int flag;
// Test case 1: any x is a solution (a = b = c = 0)
flag = quadratic_roots(0, 0, 0, roots);
printf("flag: %d\n", flag);
// Test case 2: wrong equation (a = b = 0, c != 0)
flag = quadratic_roots(0, 0, 1, roots);
printf("flag: %d\n", flag);
// Test case 3: one root (a = 0, b == 0, so the root is -c/b)
flag = quadratic_roots(0, 2, 2, roots);
printf("flag: %d, roots: %f\n", flag, roots[0]);
// Test case 4: two roots (b^2 - 4ac >= 0)
flag = quadratic_roots(3, 6, 3, roots);
printf("flag: %d, roots: %f, %f\n", flag, roots[0], roots[1]);
// Test case 5: no roots (b^2 - 4ac < 0)
flag = quadratic_roots(2, 2, -12, roots);
printf("flag: %d\n", flag);
return 0;
}
上述代码中的 quadratic_roots 函数用于计算二次方程的根。它接受四个参数:a、b、c 分别是二次方程的系数,roots 数组用于存储两个根。这个函数返回一个整数变量 flag,其值根据根的数量和类型设定。
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!