我有一个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 :(得分:9)
0.5的平方根是~0.7。如果检查失败,您的逻辑就是猜测一个较小的数字。您需要做的是添加一个额外的检测层,以查看该数字是否为&lt; 1,然后修改流程以增加下一个猜测,而不是减少它。
答案 1 :(得分:2)
如果x <1,则需要更改初始边界,因为平方根不位于0和x之间,而是位于x和1之间
double xhi, xlo, guess;
if (x > 1){
xhi = x;
xlo = 0;
guess = x / 2;
}
else{
xhi = 1;
xlo = x;
guess = (x + 1) / 2;
}
答案 2 :(得分:0)
添加一些调试输出。这将有助于您理解为什么程序在x < 1.0
时永远不会收敛到解决方案。
while (abs(guess*guess - x) > 0.000001)
{
if (guess*guess > x)
{
cout << "Changing xhi\n";
xhi = guess;
}
else
{
cout << "Changing xlo\n";
xlo = guess;
}
guess = (xhi + xlo) / 2;
cout << "guess: " << guess << endl;
}
如果您关注the Newton-Raphson method,程序将更快收敛。此外,无论x
是否大于或小于1,它都能正常工作。
double squareroot(double x)
{
/* make sure x is not negative .. no math crimes allowed! */
assert(x >= 0);
if (x == 0) return 0;
double guess = x / 2;
while (abs(guess*guess - x) > 0.000001)
{
double dx = 0.5*(guess*guess -x)/guess;
guess -= dx;
cout << "guess: " << guess << endl;
}
return guess;
}