leetcode-二分搜索:求一个数的平方根

解题思路:

  • 设double low=0,double up=x
  • double mid = (low + up) / 2
  • 如果mid * mid > x,则up = mid;如果mid * mid < x,则low = mid;如果fabs(mid * mid - x) <= 1e-6,则返回mid,否则继续迭代计算

程序如下

#include<iostream>
#include<math.h>
#include<stdlib.h>
#include<stdio.h>

using namespace std;

double sqrt(double x)
{
    double low = 0;
    double up = x;
    double mid = (low + up) / 2;
    while(fabs(low - up) >= 1e-6)
    {
        if(mid * mid > x)
            up = mid;
        else if(mid * mid < x)
            low = mid;
        else if(fabs(mid * mid - x) < 1e-6)
            return mid;
        mid = (up + low) / 2;
    }
    return mid;
}



int main(int arvc, char** argv)
{
    double in = atof(argv[1]);
    double r = sqrt(in);
    printf("r = %f\n", r);
    return 0;
}

你可能感兴趣的:(LeetCode)