954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

C++ Square Root Problem

The basic structure of the program is this:
1. issue an interactive prompt for the user to enter a non-negative number,
2. verify that the input is indeed non-negative, or that the user wishes to end the program,
3. calculate the square root of the input value, using the method to be described shortly,
4. print some information about how well the method worked,
5. go back to step 1.

Here is the square root method. Suppose the input value is in the variable a, type double. For convenience and to explain what’s going on, we’ll write the value a = b^2, but we don’t know the value of b yet (its value is sqrt(a) but we’re trying to calculate b ourselves). Start to compute a sequence of values xN by setting x0 = a. Once we know xn we can calculate xn+1 by the rule
xn+1 = ½ (xn + a/xn)
and then we just keep going until the sequence xN converges to b.

I have decided to use nested loops for the program but they aren't really working...

#include <iostream>
#include <cmath>   // Needed for rand operations.

int main ()
{
	char quit='N';
	double userInput, estimate, sqrt_answer, y,x,a;
	while (toupper(quit) != 'Y')
	{
		cout <<"enter non zero number *****:"<<flush;
		cin >> userInput;

		If (userInput <=0)
		 { 
			 cout <<"invalid. would you like to quit?(y/n):"<<flush;
			 cin>> quit;
		}
		x = a = userInput;
		y= 0;


				 //sqrt
		lasty= 0;
		for(i=0;i<=15;i++)
		{
			y=0.5*(x+a/x);
			x=y;
			if (y == lasty)
				break;
			lasty=y;


I dont really understand what to do next to make this work....
Please help me out..
Thanks

punter
Newbie Poster
2 posts since Oct 2006
Reputation Points: 10
Solved Threads: 0
 
I dont really understand what to do next to make this work.... Please help me out.. Thanks


Flow chart. That's what you need.

[tex]x_{n+1} = \frac{1}{2}(x_{n}+\frac{a}{x_{n}})[/tex]

Let's pretend you are trying to find the square root of 25. Thus in your formula abovea would be 25. That never changes. x is the variable that gets updated.

a = 25
x = 100 // arbitary start value you can choose any number
//while condition
 x = 0.5 * (x + ( a / x ))
end while
print x
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

To calculate square root without using built in math library function, visit this page:
http://bitsbyta.blogspot.com/2011/02/how-to-calculate-square-root-c.html

SaadBinSaulat
Newbie Poster
1 post since Feb 2011
Reputation Points: 9
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You