我在 C++ 中实现了自己的平方根函数以获得高达 9 点的精度,但它不起作用

I implemented my own square root function in c++ to get precision upto 9 points but it's not working

我想得到一个数字的平方根,精度高达 9 个点,所以我做了类似下面的操作,但我没有得到正确的精度。这里 e 是大于 10^9 的精度,然后 ans 也是高达 5 个精度点。我在这里做错了什么??

    #include <iostream>
    using namespace std;
    long double squareRoot(long double n) 
        { 

            long double x = n; 
            long double y = 1; 
            long double e = 0.00000000000001; 
            while (x - y > e) 
            { 
                x = (x + y) / 2; 
                y = n / x; 
            } 
            cout << x << "\n";
            return x; 
        } 

    int main() 
    {
        int arr[] = {2,3,4,5,6};
        int size = sizeof(arr)/sizeof(arr[0]);
        long double ans = 0.0;
        for(int i=0; i<size; i++)
        {
            ans += squareRoot(arr[i]);
        }

        cout << ans << "\n";
        return 0;
    }

输出为

1.41421
1.73205
2
2.23607
2.44949
9.83182

我应该怎么做才能达到9分的精度??

试试这个

cout << setprecision(10) << x << "\n";

cout << setprecision(10) << ans << "\n";

精度在两个个地方发挥作用:

  • 值本身的精度
  • 输出流的精度

如果 流都足够精确,则只能获得所需精度的输出。

在你的情况下,计算值似乎不是问题,但是,默认流精度只有五位数,即。 e.无论您的 double 值实际上有多精确,流都会在五位数后停止,并适当地四舍五入最后一位。因此,您需要将流精度提高到所需的九位数字:

std::cout << std::setprecision(9);
// or alternatively:
std::cout.precision(9);

与 e 相反,精度会一直保持到设置新精度为止。 G。 std::setw,仅适用于下一个值。