生成一个求解三阶方程的C语言代码
时间: 2024-05-13 17:20:08 浏览: 11
我可以为您提供一个求解三阶方程的C语言代码,代码如下:
```c
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, d, x1, x2, x3, p, q;
printf("请输入三阶方程的系数(a,b,c):");
scanf("%lf %lf %lf", &a, &b, &c);
d = b * b - 3 * a * c;
if (fabs(a) < 1e-6 && fabs(b) < 1e-6 && fabs(c) < 1e-6) {
printf("方程根是任意的\n");
} else if (fabs(a) < 1e-6 && fabs(b) < 1e-6) {
printf("方程无解\n");
} else if (fabs(a) < 1e-6) {
printf("方程有一个根: %lf\n", -c / b);
} else if (d > 1e-6) {
p = (-b + sqrt(d)) / (3 * a);
q = (-b - sqrt(d)) / (3 * a);
x1 = -b / (3 * a) + p + q;
x2 = (-b + 2 * p * (1 + I * sqrt(3))) / (3 * a);
x3 = (-b + 2 * q * (1 - I * sqrt(3))) / (3 * a);
printf("方程有三个复数根:\n");
printf("x1 = %lf\n", x1);
printf("x2 = %lf + %lf i\n", creal(x2), cimag(x2));
printf("x3 = %lf + %lf i\n", creal(x3), cimag(x3));
} else if (fabs(d) < 1e-6) {
x1 = -b / (3 * a) + 2 * c / (3 * a) * pow(d, -0.5);
x2 = -c / (3 * a) - pow(d, -0.5) / 3;
x3 = -c / (3 * a) + pow(d, -0.5) / 3;
printf("方程有三个实数根:\n");
printf("x1 = %lf\n", x1);
printf("x2 = %lf\n", x2);
printf("x3 = %lf\n", x3);
} else if (d < -1e-6) {
double t = acos(sqrt(-27 * a * a / d) / 2) / 3;
x1 = -b / (3 * a);
x2 = 2 * sqrt(-d / 3) * cos(t) - b / (3 * a);
x3 = 2 * sqrt(-d / 3) * cos(t + 2 * M_PI / 3) - b / (3 * a);
printf("方程有三个实数根:\n");
printf("x1 = %lf\n", x1);
printf("x2 = %lf\n", x2);
printf("x3 = %lf\n", x3);
}
return 0;
}
```
这个 C 语言代码可以求解三阶方程的根,通过输入方程的系数 a、b、c,可以输出方程的根。如果系数为零或方程无解,程序会输出相应的提示信息。当然,如果您有其他更具体的要求,我也可以进行修改和定制。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)