为什么我用C语言写如下代码时无法输出正确解? 目的:用二分法解方程a*x-e^x=b(a>0,b>0,0<x<20)
展开全部
float f(float a, float b, float x) {
return a * x + pow(2.72f, x) - b;
}
float solve(float a, float b, float epsilon) {
float low = 0f;
float high = 20f;
float x = (low + high) / 2.0f;
while(fabs(high - low) > epsilon) {
x = (low + high) / 2.0f;
if (f(a, b, low) * f(a, b, x) < 0) {
high = x;
} else {
low = x;
}
}
return x;
}
int main() {
float a, b;
scanf("%f %f", &a, &b);
if (a <= 0 || b < 1 || b >= pow(2.72f, 20)) {
printf("ERROR");
} else {
printf("solution:%.1f\n", solve(a, b, 0.01));
}
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询