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

Dani AI

Generated

Two small corrections will make the routine robust.

correctly flagged the uninitialized variable — never compare a value that hasn’t been set. was also right: floating-point iterations often oscillate, so equality checks like a == b will fail. Use an absolute-difference stop condition computed from the user’s "tolerance", add a sensible initial guess and a maximum iteration count, and validate inputs (zero and negatives). The algorithm you are using is the Newton–Raphson update for sqrt: x_{n+1} = (x_n + A / x_n) / 2.

A compact, safe pattern:

#include <cmath>
#include <limits>

double sqrt_newton(double A, int digits) {
    if (A < 0) return std::numeric_limits<double>::quiet_NaN();
    if (A == 0) return 0.0;
    double x = (A > 1.0) ? A / 2.0 : 1.0;    // initialize
    double eps = std::pow(10.0, -digits);   // tolerance -> epsilon
    const int maxIter = 1000;
    for (int i = 0; i < maxIter; ++i) {
        double next = 0.5 * (x + A / x);
        if (std::fabs(next - x) <= eps) return next;
        x = next;
    }
    return x; // fallback after maxIter
}

Printing and safety notes: use std::fixed << std::setprecision(digits) when you want digits places after the decimal (default setprecision is significant digits). Replace void main() with int main() and return 0;. Always check cin for failure and guard against division by zero if you change the initial guess. If you just want a reliable answer, std::sqrt from <cmath> is the standard and well-tested alternative.

Quick checklist for : initialize your variables, replace equality checks with fabs(diff) <= eps, compute eps from the requested decimal places, and add a maximum-iteration escape so the program cannot hang.

Recommended Answers

All 5 Replies

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.