解一元二次方程。C语言
时间: 2023-09-15 14:23:51 浏览: 180
以下是一个解一元二次方程的C语言程序:
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, x1, x2, discriminant, realPart, imaginaryPart;
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f", &a, &b, &c);
discriminant = b*b - 4*a*c;
// Real and Different Roots
if (discriminant > 0)
{
x1 = (-b + sqrt(discriminant)) / (2*a);
x2 = (-b - sqrt(discriminant)) / (2*a);
printf("Roots are %.2f and %.2f", x1, x2);
}
// Real and Equal Roots
else if (discriminant == 0)
{
x1 = (-b + sqrt(discriminant)) / (2*a);
printf("Roots are %.2f and %.2f", x1, x1);
}
// Imaginary Roots
else
{
realPart = -b/(2*a);
imaginaryPart = sqrt(-discriminant)/(2*a);
printf("Roots are %.2f+%.2fi and %.2f-%.2fi", realPart, imaginaryPart, realPart, imaginaryPart);
}
return 0;
}
在程序中,用户输入方程的系数a、b和c。程序计算判别式并根据其值确定方程的根的类型。如果判别式大于0,则有两个不同的实数根。如果判别式等于0,则有两个相等的实数根。如果判别式小于0,则有两个共轭复数根。程序输出根的类型和值。
阅读全文