二分法求根
需要输入输出正确
能够正常运行,复合题目要求.二分法
求根
#include <stdio.h>
#include <math.h>
double f(double x) {
return 2 * pow(x, 3) - 4 * pow(x, 2) + 3 * x - 6;
}
double bisection(double x1, double x2, double epsilon) {
double mid;
while ((x2 - x1) > epsilon) {
mid = (x1 + x2) / 2;
if (f(mid) == 0) {
return mid;
}
else if (f(x1) * f(mid) < 0) {
x2 = mid;
}
else {
x1 = mid;
}
}
return (x1 + x2) / 2;
}
int main() {
double x1, x2;
printf("请输入区间[x1,x2]:");
scanf("%lf %lf", &x1, &x2);
if (f(x1) * f(x2) > 0) {
printf("noroot\n");
}
else {
double root = bisection(x1, x2, 0.001);
printf("%.3lf\n", root);
}
return 0;
}