我已经在互联网上彻底搜索了这个主题,并且线程要么已经死了,要么使用与我书中描述的方法不同的方法.
这是文中的问题.
The Babylonian algorithm to compute the square root of a number n is as follows:
Make a guess at the number (you can pick n/2 as your initial guess).
Compute r = n / guess
Set guess = (guess + r) / 2
Go back to step 2 for as many iterations as necessary. The more that steps 2 and 3 are repeated, the closer guess will become to the
square root of n.
Write a program that inputs an integer for n, iterates through the
Babylonian algorithm until guess is within 1% of the previous guess,
and outputs the answer as a double.
我写了以下代码:
#include
using std::cout;
using std::cin;
using std::endl;
int main()
{
int n;
double r, guess(4), lastGuess;
cout << "Enter a number to find the square root of: ";
cin >> n;
do
{
r = n / guess;
lastGuess = guess;
guess = ( guess + r ) / 2;
// cout <
// cout <
cout << "Guess : " << guess << endl;
cout << "Last Guess 1% = " << lastGuess + ( lastGuess * 0.01 ) << endl;
cout << "r = " << r << endl;
} while( guess >= lastGuess * 0.01 );
cout << r;
return 0;
}
该程序计算r的正确答案,但尽管猜测大于1%添加到lastGuess,循环也不会终止.
当输入144作为n时,该程序产生以下输出.
....
r = 12
Guess : 12
Last Guess 1% = 12.12
r = 12
Guess : 12
Last Guess 1% = 12.12
r = 12
Guess : 12
Last Guess 1% = 12.12
r = 12
Guess : 12
Last Guess 1% = 12.12
....
根(r)是正确的(12).猜测比lastGuess(12 <12.12)少,它应该返回错误的条件,对吗?为什么循环没有结束?