Reputation: 41
I'm doing an assignment and while I have it pretty much entirely done, I've run into a problem. The program is supposed to find the square root of a number the user inputs using the Babylonian square root algorithm. I was given an example output, and mine does not quite match. Also if you see any more issues please, give me a heads up! Especially if it's about the do while loop (it was the only solution I could get that stopped an infinite loop issue I was having).
#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 the\n";
cout << "Babylonian square root algorithm until\n";
cout << "I am within .001 of the correct answer\n";
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
Upvotes: 1
Views: 124
Reputation:
Change the type of input
from int
to double
:
double input;
which changes initial value of guess = input / 2
from floor(151/2) = 75.0
to 75.5
for the expected sequence of values. Alternatively, cast the enumerator input
to a double
in the expression with:
guess = (double) input / 2;
or more elegantly via implicit type conversion by using floating point value as the divisor at suggested by @AlanBirtles:
guess = input / 2.0;
To fix the loop test:
#include <math.h>
...
do {
...
} while(fabs(test - guest) > 0.001);
Upvotes: 1