点击查看代码
#include<cstdio>
#pragma warning(disable:4996)
//给定一个定义在[L,R]上的单调函数f(x)=x^2-2,求方程f(x)=0的根,即根号2的值
const double eps = 1e-5; //精度要求eps是10^-5
double f(double x) {
return x * x - 2;
}
double solve(double L, double R) {
double left = L, right = R, mid = 0;
//还没达到精度要求就继续计算
while (right - left > eps) {
mid = left + (right - left) / 2;
if (f(mid) > 0) { //f(mid)大于0,进入[left,mid]查找
right = mid;
}
else { //f(mid)小于等于0,进入[mid,right]查找
left = mid;
}
}
return mid; //mid就是f(x)=0在[1,2]区间内的根
}
int main() {
printf("%f", solve(1, 2)); //区间[1,2]
return 0;
}