【C语言】7.2 求一元二次方程的根
#include <stdio.h>
#include <math.h>
// 根的判别式大于0
void deltaMoreThanZero(int a, int b, int c) {
float root1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);
float root2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);
printf("该方程的根为: %.2f 和 %.2f\n", root1, root2);
}
// 根的判别式小于0
void deltaLessThanZero(int a, int b, int c) {
printf("该方程无实数根。");
}
// 根的判别式等于0
void deltaEqualToZero(int a, int b, int c) {
float root = -b / (2 * a);
printf("该方程的根为: %.2f\n", root);
}
int main() {
float a, b, c;
printf("请输入a, b, c: ");
scanf("%f,%f,%f", &a, &b, &c);
float delta = pow(b,2) - 4*a*c;
if (delta > 0) {
deltaMoreThanZero(a, b, c);
} else if (delta == 0) {
deltaEqualToZero(a, b, c);
} else {
deltaLessThanZero(a, b, c);
}
return 0;
}
扫描二维码,在手机上阅读
收藏