c语言实现巴比伦求平方算法,在C语言中获得平方根的巴比伦算法的无限循环

我已经在互联网上彻底搜索了这个主题,并且线程要么已经死了,要么使用与我书中描述的方法不同的方法.

这是文中的问题.

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)少,它应该返回错误的条件,对吗?为什么循环没有结束?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值