用c语言编写程序解一元二次方程
时间: 2024-02-01 12:14:46 浏览: 69
下面是一个简单的 C 语言程序,用于解一元二次方程:
```c
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c, x1, x2, discriminant, realPart, imaginaryPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
x1 = (-b + sqrt(discriminant)) / (2 * a);
x2 = (-b - sqrt(discriminant)) / (2 * a);
printf("Roots are real and different.\n");
printf("x1 = %.2lf and x2 = %.2lf\n", x1 , x2);
}
else if (discriminant == 0) {
x1 = -b / (2 * a);
printf("Roots are real and same.\n");
printf("x1 = x2 = %.2lf\n", x1);
}
else {
realPart = -b / (2 * a);
imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("Roots are complex and different.\n");
printf("x1 = %.2lf+%.2lfi and x2 = %.2lf-%.2lfi\n", realPart, imaginaryPart, realPart, imaginaryPart);
}
return 0;
}
```
运行程序后,程序会提示您输入方程的系数 a、b 和 c。然后,程序会计算方程的判别式,并根据判别式的值输出方程的根。如果判别式为正,则方程有两个实根。如果判别式为零,则方程有一个实根。如果判别式为负,则方程有两个复根。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)