【发布时间】:2018-09-04 21:46:18
【问题描述】:
我遇到了一个问题,要编写一个 C 程序来求解方程 ax2+bx+c=0,其中 a , b 和 c 是double 类型的系数。任何系数都可以为零。在这个问题中,我不清楚如何处理 double 变量。
这是我的代码。至于现在,我知道我的程序无法区分两个根和无限多个根。它也没有检测到“线性方程情况”。我怎样才能让它检测到无限数量的解决方案?如果 b > 0,cmets 还建议我在判别式之前用减号计算根,然后使用 Viet 定理。我知道这是因为将两个数字相加总是更准确。我还想我应该对 b
#include <stdio.h>
#include <math.h>
#include <float.h>
int main() {
double a, b, c, x1, x2;
scanf("%lf", &a);
scanf("%lf", &b);
scanf("%lf", &c); // just reading variables
//ax^2+bx+c=0
if ((b * b - 4 * a * c) < 0) {
printf("no");
} else {
x1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a); //calculating roots
x2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);
if ((fabs((a * x1 * x1 + b * x1 + c)) < DBL_EPSILON) & (fabs((a * x2 * x2 + b * x2 + c)) < DBL_EPSILON)) { //plugging the roots in
if (fabs((x1 - x2)) < DBL_EPSILON) { //checking if the roots are equal
printf("%lf", &x1); // if they are equal, we print only one of them
} else {
printf("%lf", &x1); // if they are not equal, we print both.
printf("\n %lf", &x2);
}
} else { // if there are no two valid roots
if ((fabs((a * x1 * x1 + b * x1 + c)) < DBL_EPSILON)) // we try to find one root.
printf("%lf", &x1);
if (fabs((a * x2 * x2 + b * x2 + c)) < DBL_EPSILON)
printf("%lf", &x2);
if ((fabs((a * x1 * x1 + b * x1 + c)) > DBL_EPSILON) & (fabs((a * x2 * x2 + b * x2 + c)) > DBL_EPSILON)) // if both of the plugged roots don't satisfy the equation
printf("no");
}
}
return 0;
}
【问题讨论】:
标签: c floating-point double