gpt4 book ai didi

C++ 平方根函数错误

转载 作者:太空狗 更新时间:2023-10-29 23:35:32 25 4
gpt4 key购买 nike

我有一个计算整数平方根的 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";
}

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

if (x<1) {
xhi = 1;
xlo = x;
guess = (x + 1) / 2;
}

最佳答案

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

关于C++ 平方根函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34782086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com