fork(1) download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. double f(double x) {
  7. return 0.25 * x * x - 2.0;
  8. }
  9.  
  10. int main() {
  11. double x0 = 2.0; // pierwszy punkt startowy
  12. double x1 = 4.0; // drugi punkt startowy
  13. double x2; // kolejne przybliżenie
  14. double eps = 0.0001; // dokładność
  15. int iter = 0;
  16. int maxIter = 100;
  17.  
  18. do {
  19. if (fabs(f(x1) - f(x0)) < 1e-12) {
  20. cout << "Blad: dzielenie przez zero!" << endl;
  21. return 1;
  22. }
  23.  
  24. x2 = x1 - f(x1) * (x1 - x0) / (f(x1) - f(x0));
  25.  
  26. x0 = x1;
  27. x1 = x2;
  28. iter++;
  29.  
  30. } while (fabs(f(x2)) > eps && iter < maxIter);
  31.  
  32. cout << "Miejsce zerowe: x = " << x2 << endl;
  33. cout << "Liczba iteracji: " << iter << endl;
  34.  
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Miejsce zerowe: x = 2.82842
Liczba iteracji: 4