#include <iostream>
usingnamespace std;
int main()
{
int n, count(10);
double answer_n, guess, r;
cout << "This program will compute the square root\n";
cout << "of a number using the Babylonian algorithm.\n";
cout << "Please enter a whole number and press the return key:\n";
cin >> n;
cout << "Please enter a 'guess' number to divide by:\n";
cin >> guess;
r = n/guess;
guess = (guess + r)/2;
while (count > 0)
{
r = n/guess;
guess = (guess + r)/2;
if (guess <= (guess * 0.01) + guess)
answer_n = guess;
else
r = n/guess;
guess = (guess + r)/2;
count-=1;
}
cout << "The sqaure root of "<< n << " is " << answer_n;
cout << endl;
return 0;
}
But some coding are going still out of my understanding, that why we have used if statement here
if (guess <= (guess * 0.01) + guess)
and second what is in else statement?
1 2 3 4 5
else
r = n/guess;
guess = (guess + r)/2;
count-=1;
Can you explain me only and the program is working 100%.
Line 24 is comparing the calculated value of guess to see if it is within the desired range for an answer.
Line 26, the else, is only two lines: line 26 and line 27. That is because an if or an else only has one line after it, unless you group it with curly braces.
because this line is the only line executed when the else is valid
1 2
else
r = n/guess;
and these lines are always executed regardless of the if/else. If you remove them you will not be doing something that you were before, as koothkeeper said.