我无法解决的问题是我如何找到0到1之间的数字sqrt。之后我觉得一切正常。导致此程序崩溃的唯一输入数字是0(不包括)和1(不包括)
之间的数字有任何帮助吗?
#include <iostream>
#include <cmath>
#include <cassert>
#include <stdlib.h>
#include <cmath>
using namespace std;
double squareroot(double x) /* computes the square root of x */
{
assert( x >= 0 ); /* make sure x is not negative*/
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.00001 )
{
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" ;
}
答案 0 :(得分:3)
由于这一行,您的程序崩溃了:
while (abs(guess*guess-x) > 0.00001 )
如果数字介于0和1之间,则算法将始终生成大于0.00001的数字,从而导致无限循环。修复方法是将算法更改为另一种平方根近似技术(参见Newton方法,不动点定理,多项式逼近技术等)。
提示:尝试跟踪您的代码,看看即使您需要将其写在纸上也会发生什么