生成一个求解四阶方程的C语言代码
时间: 2024-05-29 21:09:31 浏览: 69
以下是一个求解四阶方程的C语言代码:
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, d;
float discriminant, root1, root2, root3, root4;
printf("Enter the coefficients of the fourth order equation:\n");
printf("a: ");
scanf("%f", &a);
printf("b: ");
scanf("%f", &b);
printf("c: ");
scanf("%f", &c);
printf("d: ");
scanf("%f", &d);
if (a == 0)
{
printf("Error: a cannot be zero!\n");
}
else
{
discriminant = pow(b, 2) - 4 * a * c;
if (discriminant > 0)
{
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
root3 = (-b + sqrt(-discriminant)) / (2 * a);
root4 = (-b - sqrt(-discriminant)) / (2 * a);
printf("Root 1 = %.2f\nRoot 2 = %.2f\nRoot 3 = %.2fi\nRoot 4 = %.2fi\n", root1, root2, root3, root4);
}
else if (discriminant == 0)
{
root1 = -b / (2 * a);
printf("Root 1 = Root 2 = %.2f\n", root1);
}
else
{
root1 = -b / (2 * a);
root2 = sqrt(-discriminant) / (2 * a);
root3 = -b / (2 * a);
root4 = -sqrt(-discriminant) / (2 * a);
printf("Root 1 = %.2f + %.2fi\nRoot 2 = %.2f - %.2fi\nRoot 3 = %.2f + %.2fi\nRoot 4 = %.2f - %.2fi\n", root1, root2, root3, root4, root1, -root2, root3, -root4);
}
}
return 0;
}
阅读全文