SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
C++ Basics
Exercise:
Programming Projects
Question:12 | ISBN:9780321531346 | Edition: 7

Question

12. The Babylonian algorithm to compute the square root of a number n is as follows:

1. Make a guess at the answer (you can pick n/2 as your initial guess).

2. Compute r = n / guess

3. Set guess = (guess + r) / 2

4. 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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

//Include header files for execute C++ program
#include <iostream> 
#include <math.h>   
#include <conio.h>  
using namespace std;

//main function
int main()
{

  //variables declaration
  int n;
  double r;
  double guess;
  double initialGuess;
  //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
   cout<<"Please enter an integer n : ";
  cin>>n;
  //Calculating value of guess
  guess = (double) n/2;
  while( guess*guess < 0.99*(double)n ||
                        guess*guess > 1.01*(double)n)
  {    
   	initialGuess = guess; 		
 	r = (double) n/guess;
 	guess = (double)(guess+r)/2;
 }
  	cout << "The square root of a number n =" 
  	     << n <<" is " << guess;
 }

Output 1 for the program code:

Please enter an integer n : 121                                                                     The square root of a number n =121 is 11.0002 

Output 2 for the program code:

Please enter an integer n : 1441                                                                                           
The square root of a number n =1441 is 38.0495 

 

1 0

Discussions

Post the discussion to improve the above solution.