练习该程序之前,你需要学习逻辑运算符和关系运算符。您也必须知道IF ELSE语句。
ax2+ bx + c = 0, where a, b and c are real numbers and a != 0
b2 – 4ac 是一元二次方程的判别式(discriminant)。确定了根的性质:
- 如果判别式大于 0,则根为实数且不同;
- 如果判别式等于 0,则根为实数且相等;
- 如果判别式小于 0,则根复杂且不同。

#include <math.h>
#include <stdio.h>
int main() {
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
discriminant = b * b - 4 * a * c;
// condition for real and different roots
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
// condition for real and equal roots
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else {
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart, imagPart);
}
return 0;
}
|
1 2 3 4 |
Enter coefficients a, b and c: 2.3 4 5.6 root1 = -0.87+1.30i and root2 = -0.87-1.30i |
sqrt()函数用来计算一个数的平方根。
除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!