問題:手寫代碼實現sqrt函數,即求一個整數的平方根ios
分析:二分查找思想函數
1 #include <iostream>
2 3 using namespace std; 4 5 int sqrt(int x) 6 { 7 long left = 0; 8 9 if(x == 1) 10 return 1; 11 long right = x; 12 13 long mid = left + (right - left)/2; 14 while(left + 1 < right) 15 { 16 if(x > mid * mid) 17 { 18 left = mid; 19 } 20 else if(x < mid * mid) 21 { 22 right = mid; 23 } 24 else 25 { 26 return mid; 27 } 28 mid = left + (right - left)/2; 29 } 30 return left; 31 } 32 33 int main() 34 { 35 cout << "144 的平方根爲:" << sqrt(144) << endl; 36 return 0; 37 }