fork download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. double babylonianSquareRoot(double n) {
  5. if (n < 0) {
  6. std::cerr << "Error: Cannot compute square root of a negative number." << std::endl;
  7. return -1; // Return -1 for invalid input
  8. }
  9.  
  10. double x = n; // Initial guess
  11. double y = 1.0; // Second guess
  12. double e = 0.000001; // Tolerance for convergence
  13.  
  14. while ((x - y) > e) {
  15. x = (x + y) / 2.0; // Update x as the average of x and y
  16. y = n / x; // Update y as n divided by the new x
  17. }
  18.  
  19. return x; // Return the computed square root
  20. }
  21.  
  22. int main() {
  23. double number;
  24.  
  25. std::cout << "Enter a number to compute its square root: ";
  26. std::cin >> number;
  27.  
  28. double result = babylonianSquareRoot(number);
  29.  
  30. if (result != -1) { // Check for valid result
  31. std::cout << "The square root of " << number << " is approximately: " << result << std::endl;
  32. }
  33.  
  34. return 0;
  35. }
  36.  
Success #stdin #stdout 0.01s 5292KB
stdin
5
stdout
Enter a number to compute its square root: The square root of 5 is approximately: 2.23607