fork(1) download
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. // Definicja funkcji
  6. double f(double x)
  7. {
  8. return 0.25 * x * x - 2;
  9. }
  10.  
  11. int main()
  12. {
  13. double a = 2.0;
  14. double b = 4.0;
  15. double c;
  16. double eps = 1e-6; // dokładność
  17. int iteracje = 0;
  18.  
  19. // Sprawdzenie warunku f(a)*f(b) < 0
  20. if (f(a) * f(b) >= 0)
  21. {
  22. cout << "Warunek f(a) * f(b) < 0 nie jest spełniony." << endl;
  23. return 0;
  24. }
  25.  
  26. // Metoda bisekcji
  27. while ((b - a) / 2 > eps)
  28. {
  29. c = (a + b) / 2;
  30.  
  31. if (f(a) * f(c) < 0)
  32. b = c;
  33. else
  34. a = c;
  35.  
  36. iteracje++;
  37. }
  38.  
  39. // Przybliżone miejsce zerowe
  40. double miejsce_zerowe = (a + b) / 2;
  41.  
  42. cout << "Miejsce zerowe: " << miejsce_zerowe << endl;
  43. cout << "Liczba iteracji: " << iteracje << endl;
  44.  
  45. return 0;
  46. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Miejsce zerowe: 2.82843
Liczba iteracji: 20