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 ,kenrick Mock
Chapter:
Flow Of Control
Exercise:
Programming Projects
Question:9 | ISBN:9780132846813 | Edition: 5

Question

(This is an extension of an exercise from Chapter 1.) The Babylonian algorithm to compute the square root of a positive 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 steps 2 and 3 are repeated, the closer guess will become to the square root of n.

Write a program that inputs a double for n, iterates through the Babylonian algorithm until the guess is within 1% of the previous guess, and outputs the answer as a double to two decimal places. Your answer should be accurate even for large values of n.


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 = 555                                                                                            
The square root of a number n =555 is 23.5593 

Output 2 for the program code:

Please enter an integer n = 1221                                                                                           
The square root of a number n =1221 is 34.9885    

 

0 0

Discussions

Post the discussion to improve the above solution.