learn && wrong:
1、f(mid)与2的关系,改成与o的关系
2、f(x)更改一下
3、如果递减,只需要把f(mid)改成小于号
#include <iostream>
const double eps = 1e-5; //精度为10的-5次方(!!!)
double f(double x) { //计算f(x)
return ...
}
double calsqrt() {
double left = 1, right = 2, mid; //[left,right] = [1,2]
while (right - left > eps) {
mid = (right - left) / 2;
if (f(mid) > 0) {
right = mid;
}
else if(f(mid) < 0) {
left = mid;
}
}
return mid;
}
#include <iostream>
const double eps = 1e-5; //精度为10的-5次方(!!!)
double f(double x) { //计算f(x)
return x * x;
}
double calsqrt() {
double left = 1, right = 2, mid; //[left,right] = [1,2]
while (right - left > eps) {
mid = (right - left) / 2;
if (f(mid) > 2) {
right = mid;
}
else if(f(mid) < 2) {
left = mid;
}
}
return mid;
}
网友评论