巴比伦平方根算法输出不匹配示例



我正在做一项作业,虽然我已经基本完成了,但我遇到了一个问题。该程序应该使用巴比伦平方根算法找到用户输入的数字的平方根。我得到了一个示例输出,我的输出不太匹配。此外,如果你看到任何更多的问题,请给我一个提醒!特别是当它是关于do while循环(这是唯一的解决方案,我可以得到停止无限循环的问题,我有)。

#include <ios>
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
std::cout << std::fixed << std::setprecision(4);
//variables
int input;
double guess, r, check, test;
//input
cout << "Enter a number and I will apply then";
cout << "Babylonian square root algorithm untiln";
cout << "I am within .001 of the correct answern";
cin >> input;
cout << "You input " << input << "n";
//calculate
guess = input / 2;
do {
test = guess;
r = input / guess;
guess = (guess + r) / 2;
cout << "nguessing " << guess;
} while (guess != test); //while end
//check
check = guess * guess;
cout << "nThe Babylons algorithm gives " << guess;
cout << "nChecking: " << guess << " * " << guess << " = " << check << "n";
} //main end
**Example output:** 

Enter a number and I will apply the Babylonian square root algorithm 
until I am withing .001 of the correct answer. 
151 
You entered 151 
guessing 38.75 
guessing 21.3234 
guessing 14.2024 
guessing 12.4172 
guessing 12.2889 
The Babylons algorithm gives 12.2889 
Checking: 12.2889 * 12.2889 = 151.016 
Press any key to continue . . .
**My Output:**
Enter a number and I will apply the
Babylonian square root algorithm until
I am within .001 of the correct answer
151
You input 151
guessing 38.5067
guessing 21.2140
guessing 14.1660
guessing 12.4127
guessing 12.2888
guessing 12.2882
guessing 12.2882
guessing 12.2882
The Babylons algorithm gives 12.2882
Checking: 12.2882 * 12.2882 = 151.0000

input的类型从int更改为double:

double input;

guess = input / 2的初始值从floor(151/2) = 75.0更改为75.5。或者,使用

将枚举数input强制转换为表达式中的double:
guess = (double) input / 2;

或者更优雅地通过隐式类型转换使用浮点值作为除数@AlanBirtles建议的:

guess = input / 2.0;

修复循环测试:

#include <math.h>
...
do {
...
} while(fabs(test - guest) > 0.001);