- 基础算法的灵活应用能力(二分法学过数据结构的同学都知道,但不一定往这个方向考虑;如果学过数值计算的同学,应该还要能想到牛顿迭代法并解释清楚)
- 退出条件设计
查找,如: a) high=>1.5 b) low=>1.4 c) mid => (high+low)/2=1.45 d) 1.45*1.45>2 ? high=>1.45 : low => 1.45 e) 循环到 c)
a) 前后两次的差值的绝对值<=0.0000000001, 则可退出
const double EPSILON = 0.0000000001;
double sqrt2() {
double low = 1.4, high = 1.5;
double mid = (low + high) / 2;
while (high - low > EPSILON) {
if (mid * mid > 2) {
high = mid;
} else {
low = mid;
}
mid = (high + low) / 2;
}
return mid;
}