This program uses an ancient method to find the square root.

But the problem is that it only works with certain numbers not all the numbers I input.
I would like to know if I am doing anything wrong.

I would appreciate any help I could get with this.

#include<iostream>
#include<iomanip>

using std::setprecision;
using std::cout;
using std::cin;

void main()

{
	double number;
	double divisor = 1.0000;
	double quotient;
	int tolerance;
	char result;
	
	do{	
	cout<<"Enter the number to find the square root: ";
	cin>>number;


	cout<<"\nEnter a number (1-9) to get a specific tolerance: ";
	cin>>tolerance;

	while(divisor!=quotient)
	{
		quotient = number/divisor;             // Using the method of averages
		
		divisor = (divisor + quotient) / 2;	
			
			if(quotient == divisor)
			{
				cout<<"\nThe Square Root is: "<<setprecision(tolerance)<<divisor<<'\n';
			}//close if
	
	
	}// close while

cout<< "\nDo you want to try again ? (y/n) ";
cin >> result;
cout<<'\n';   
}while(result == 'y');

}//close main

But the problem is that it only works with certain numbers not all the numbers I input.

I don't suppose you could tell us what working and nonworking values might be?

I would like to know if I am doing anything wrong.

Your loop checks quotient before it is initialized for one.

for an example the square root of 26,23,24.... and a whole bunch of other values I tried does not give an answer the executable just hangs without doing anything.

but the square root of 20 gives the right answer and perfect squares gives the right answer too.

Due to precision limits in floating point approximations, you are running into cycles where the quotient flops back and forth between two very close approximations.

Instead of testing (divisor != quotient) and (divisor == quotient), you need to see if they are sufficiently close, e.g. test (abs(divisor - quotient) < epsilon), or (abs(divisor - quotient) >= epsilon).

If this a homework assignment, I bet you're supposed to let epsilon be 1/(10^tolerance)

what do you mean by epsilon

in the code (abs(divisor-quotient)>=epsilon)

what do you mean by epsilon

in the code (abs(divisor-quotient)>=epsilon)

For some inputs, you're never going to get divisor == quotient to come out true. You need to test if they are sufficiently close. E.g. if they are less than epsilon distance apart, where epsilon is some small number, such as 0.000001

This article has been dead for over six months. Start a new discussion instead.