fork download
  1. #include <iostream>
  2. #include <cmath> // dla std::abs
  3. #include <iomanip> // dla std::setprecision
  4.  
  5. double sqrtNewton(double x, double epsilon = 1e-6) {
  6. if (x < 0) {
  7. std::cerr << "Błąd: liczba ujemna!" << std::endl;
  8. return -1;
  9. }
  10. if (x == 0) return 0;
  11.  
  12. double y = x;
  13. while (true) {
  14. double y_next = 0.5 * (y + x / y);
  15. if (std::abs(y_next - y) < epsilon)
  16. break;
  17. y = y_next;
  18. }
  19. return y;
  20. }
  21.  
  22. int main() {
  23. double liczba = 15.0;
  24. double epsilon = 0.001;
  25.  
  26. double wynik = sqrtNewton(liczba, epsilon);
  27.  
  28. // Ustawiamy 4 miejsca po przecinku
  29. std::cout << std::fixed << std::setprecision(4);
  30. std::cout << "Przybliżony pierwiastek kwadratowy z " << liczba
  31. << " wynosi: " << wynik << std::endl;
  32.  
  33. return 0;
  34. }
  35.  
Success #stdin #stdout 0.01s 5320KB
stdin
15
stdout
Przybliżony pierwiastek kwadratowy z 15.0000 wynosi: 3.8730