C++ Square Root Function Bug

Gab*_*iel 2 c++ square-root

我有一个c ++算法,可以计算整数的平方根.除了一个缺陷外,该程序可以正常运行.它无法计算低于1的数字的平方根.例如,它无法计算.5或.9或.0000001等的平方根,但在所有其他情况下按计划工作.我有X设置所以它不允许负输入,但我仍然不明白为什么它不会返回任何小于1的值.

include <iostream>
#include <cmath>
#include <cassert>

using namespace std;

double squareroot(double x)

{ /* computes the square root of x */

  /* make sure x is not negative .. no math crimes allowed! */
    assert(x >= 0);
    if (x == 0) return 0;

    /* the sqrt must be between xhi and xlo */
    double xhi = x;
    double xlo = 0;
    double guess = x / 2;

    /* We stop when guess*guess-x is very small */

    while (abs(guess*guess - x) > 0.000001)
    {
        if (guess*guess > x)  xhi = guess;
        else xlo = guess;
        guess = (xhi + xlo) / 2;
    }

    return guess;
}

/* Test Stub */


int main()
{
    double testvalue;
    cout << "\n Enter a TestValue= ";
    cin >> testvalue;
    cout << endl;
    double testresult = squareroot(testvalue);
    cout << "\n Square Root= " << testresult << "\n";
}
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助!我能够通过使用以下方法解决问题:

if (x<1) {
    xhi = 1;
    xlo = x;
    guess = (x + 1) / 2;
}
Run Code Online (Sandbox Code Playgroud)

小智 9

0.5的平方根是~0.7.如果检查失败,您的逻辑就是猜测一个较小的数字.您需要做的是添加一个额外的检测层以查看数字是否<1,然后修改流量以增加下一个猜测而不是减少它.