代码改变世界

正整数求n不用sqrt

2020-03-20 12:08  legend聪  阅读(195)  评论(0编辑  收藏  举报

二分法求根,四舍五入可以用round函数,正整数要用double来取。

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 
#include<iostream>
using namespace std;
#define ACCURACY 0.001 
double newSqrt(double n)
{
    double low, high, mid, tmp;
    // 获取上下界 
    if (n > 1) {
        low = 1;
        high = n;
    }
    else {
        low = n;
        high = 1;
    }
    // 二分法求开方 
    while (low <= high) {
        mid = (low + high) / 2.000;

        tmp = mid * mid;

        if (tmp - n <= ACCURACY && tmp - n >= ACCURACY * -1) {
            return mid;
        }
        else if (tmp > n) {
            high = mid;
        }
        else {
            low = mid;
        }
    }
    return -1.000;
}

int main(void)
{
    double n, res;
    cin >> n;
    res = newSqrt(n);
    printf("%lf\n", res);

    return 0;
}

还可以用牛顿迭代法

#include<cstdio>
#include<iostream>
using namespace std;
#define accuracy 0.01
int main()
{
    double n;
    cin >> n;
    double x1;
    x1 = 1;
    while (abs(x1*x1 - n)>accuracy)
    {
        x1= (x1 + n / x1) / 2.00;
    }
    cout << round(x1);
}