本帖最后由 涛行 于 2020-10-10 01:04 编辑
本人小白一枚,今天写了如下解一元二次方程的代码,结果当输出虚数解是,虚部永远是0.00000,往大佬们帮我看看什么情况,谢谢大佬
[C] 纯文本查看 复制代码 #include<stdio.h>
#include<math.h>
void root(double a, double b, double c);
int main()
{
double a, b, c;
printf("ax^2+bx+c=0\nPlease input a,b,c:");
scanf("%lf%lf%lf", &a, &b, &c);
printf("\n\n");
root(a, b, c);
return 0;
}
void root(double a, double b, double c)
{
double d, x1, x2, Re, Im;
if (a == 0 && b == 0 && c == 0)printf("方程有无数解。");
else if (a == 0 && b == 0 && c != 0)printf("该方程无解。");
else if (a == 0 && b != 0)printf("该方程有实根,且为x=%lf", -b / c);
else if (a != 0)
{
d = b * b - 4 * a * c;
if (d = 0)
printf("方程有两个相等的实根,且为x1=x1=%lf", -b/(2*a));
else if (d > 0)
{
x1 = (-b + sqrt(d)) / (2 * a);
x2 = (-b - sqrt(d)) / (2 * a);
printf("方程有两个不等的实根,且为x1=%lf,x2=%lf");
}
else
{
Re = -b / (2 * a);
Im = sqrt(-d) / (2 * a);
printf("方程有两个虚根,且x1的实部为%lf,虚部为%lfi,\n\t\t\t\b\b\b\b\b\bx2的实部为%lf,虚部为-%lfi", Re, Im, Re, Im);
}
}
} |