fork(1) download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. int main() {
  7. double a = 5.0; // dodatnia liczba rzeczywista
  8. double x = a; // przybliżenie początkowe
  9. double eps = 0.0001; // dokładność
  10. int iter = 0;
  11. int maxIter = 100;
  12.  
  13. if (a <= 0) {
  14. cout << "Liczba musi byc dodatnia!" << endl;
  15. return 1;
  16. }
  17.  
  18. // Metoda Newtona-Raphsona
  19. while (fabs(x * x - a) > eps && iter < maxIter) {
  20. x = 0.5 * (x + a / x);
  21. iter++;
  22. }
  23.  
  24. cout << "Przyblizona wartosc sqrt(" << a << ") = " << x << endl;
  25. cout << "Liczba iteracji: " << iter << endl;
  26.  
  27. return 0;
  28. }
  29.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Przyblizona wartosc sqrt(5) = 2.23607
Liczba iteracji: 4