What is the mean of this coding?

Jan 26, 2016 at 7:01pm
I am solving a problem "Find square root of a number n through Babylonian algorithm"

I found following solution coding at http://www.cplusplus.com/.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
using namespace 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%.
Last edited on Jan 27, 2016 at 8:32am
Jan 26, 2016 at 8:06pm
For the algorithm see this: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method


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.
Jan 27, 2016 at 7:13am
Is there any other solution of above problem?
Jan 27, 2016 at 7:47am
Is following method correct?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

#include <iostream>
using namespace std;
int main()
{
	double num, r, count = 10;
	double answer, your_guess;

	cout << "Enter a whole number of which you want to find squre root:- ";
	cin >> num;
	cout << "Enter your guess here:- ";
	cin >> your_guess;

	do
	{
		r = num/your_guess;
		your_guess = (your_guess + r)/2;
		answer = your_guess;
	} while (your_guess >= (your_guess * 0.01) + your_guess);

	cout << "Your square root is ";
	cout << answer;
}
Jan 27, 2016 at 8:30am
#kootheKeeper

But when I remove these lines

1
2
3
4
5
6
7

else
r = n/guess;
guess = (guess + r)/2;

count-=1;


Why program stops working in first coding?
Last edited on Jan 27, 2016 at 8:31am
Jan 27, 2016 at 3:39pm
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.

1
2
guess = (guess + r)/2;
count-=1;
Topic archived. No new replies allowed.