最近有人贴出BAT的面试题,题目链接。
就是实现系统的开根号的操作,并且要求一定的误差,其实这类题就是两种方法,二分法
和牛顿迭代
,现在用OC的方法实现如下:
第一:二分法实现
-(double)sqrt_binary:(int)num {
double x = sqrt(num);
double y = num / 2;
double low = 0.0;
double up = num;
int count = 1;
while (fabs(y-x) > 0.000000001) {
NSLog(@"--count:%d %f",count,y);
count ++;
if (y * y > num) {
up = y;
y = low + (up - low)/2;
}else{
low = y;
y = up -(up-low)/2;
}
}
return y;
}
//调用
double result = [self sqrt_binary:5];
NSLog(@"my result:%f--real result:%f",result,sqrt(5));
第二:牛顿迭代
-(double)sqrt_newton:(int)num {
double x = sqrt(num);
double y = num/2;
int count = 1;
while (fabs(y-x) > 0.000000001) {
NSLog(@"--count:%d %f",count,y);
count ++;
y = (y + num/y)/2.0;
}
return y;
}
//调用
double result = [self sqrt_newton:5];
NSLog(@"my result:%f--real result:%f",result,sqrt(5));