c语言 求一元二次方程的解 包括虚数解
时间: 2023-07-13 14:26:04 浏览: 192
好的,以下是求解一元二次方程的完整C语言代码,包括实数解和虚数解:
```c
#include <stdio.h>
#include <math.h>
int main() {
float a, b, c, discriminant, root1, root2, realPart, imaginaryPart;
printf("请输入一元二次方程的系数:\n");
printf("a = ");
scanf("%f", &a);
printf("b = ");
scanf("%f", &b);
printf("c = ");
scanf("%f", &c);
discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("方程的实数解为:root1 = %.2f, root2 = %.2f\n", root1, root2);
} else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("方程的实数解为:root1 = root2 = %.2f\n", root1);
} else {
realPart = -b / (2 * a);
imaginaryPart = sqrt(-discriminant) / (2 * a);
printf("方程的复数解为:root1 = %.2f + %.2fi, root2 = %.2f - %.2fi\n", realPart, imaginaryPart, realPart, imaginaryPart);
}
return 0;
}
```
输入a、b、c三个系数后,程序会根据判别式的值进行不同的计算,输出实数解或者虚数解。
阅读全文