previous | start | next

Example: No Function

Here is the example program that computed square roots without using the predefined sqrt function:

    1   int main()
    2   {
    3   
    4     double x, y;
    5     cout << "Enter a positive number: ";
    6     cin >> x;
    7   
    8     y = ( 1.0 + x ) /2;
    9   
   10     while( fabs(x - y * y) > 0.0001 ) {
   11       y = (y + x/y)/2;
   12     }
   13     cout.setf(ios::fixed);
   14     cout.precision(4);
   15   
   16     cout << "x = " << x << endl;
   17     cout << "y = " << y << endl;
   18     cout << "y*y = " << y * y << endl;
   19   
   20     return 0;
   21   }


previous | start | next