SHARE
TWEET

LW4 sqrt

parad0xxxxx Jan 24th, 2020 70 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7.     double x, precision;
  8.  
  9.     cout << "Enter X: ";
  10.     cin >> x;
  11.  
  12.     if (x <= 0) {
  13.         cout << "X must be positive and larger than 0. Can't continue. Farewell.\n\n";
  14.         return 0;
  15.  
  16.     }
  17.     else {
  18.         cout << "Enter precision: ";
  19.         cin >> precision;
  20.  
  21.         double low = 1;
  22.         double high = x;
  23.         double mid = 0;
  24.  
  25.         while (fabs(mid * mid - x) > precision) {
  26.                 mid = low + (high - low) / 2;
  27.                 if (mid * mid > x) {
  28.                     high = mid;
  29.                 }
  30.                 else {
  31.                     low = mid;
  32.                 }
  33.  
  34.             }
  35.    
  36.         cout << "Square root of " << x << " is: " << mid << endl << endl;
  37.  
  38. //check here        cout << "sqrt of " << x << " is: " << sqrt(x) << endl << endl;
  39.  
  40.         return 0;
  41.  
  42.     }
  43.  
  44. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top