题目:
实现sqrt(x)
思路:一般都是使用二分法,但是也可以使用牛顿法来实现更高的速度
#include <iostream> #include <string> #include <stdlib.h> using namespace std; int Sqrt(int num) { if(num == 1 && num == 0) return num; int low =1,high = num/2+1; int mid; while(low <= high) { mid = (high+low)/2; if(mid*mid<=num && (mid+1)*(mid+1)>num) return mid; if(mid*mid < num) low =mid+1; else high = mid-1; } return 0; } double SqrtSecond(double num) { const double eps = 0.000001; double low = 0; double high = num; double mid; while((high-low)>eps) { mid = (low+high)/2; if(mid*mid== num) return mid; if(mid*mid > num) high = mid; else low = mid; } return mid; } int main() { cout<<SqrtSecond(2)<<endl; cout<<sizeof(float)<<" "<<sizeof(double)<<endl; return 0; }
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44937311