C++ Examples -Square Root (original) (raw)

FunctionX - Practical Learning Logo Square Root Calculation

This is an example function that calculates the square root of a number:

#include using namespace std;

double Abs(double Nbr) { if( Nbr >= 0 ) return Nbr; else return -Nbr; }

double SquareRoot(double Nbr) { double Number = Nbr / 2; const double Tolerance = 1.0e-7;

**do Number = (Number + Nbr / Number) / 2;**
**while( Abs(Number * Number - Nbr) > Tolerance);**

**return Number;**

}

int main() { double Number = 1448.64; double Nbr = SquareRoot(Number);

cout << "The square root of " << Number << " is " << Nbr << "\n\n";

return 0;

}

Here is an example of running the program:

The square root of 1448 is 38.0526 Press any key to continue