fork download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. // Funkcja: f(x) = x^2 - 2
  5. double f(double x)
  6. {
  7. return x * x - 2;
  8. }
  9.  
  10. int main()
  11. {
  12. double a = 1.0; // początek przedziału
  13. double b = 2.0; // koniec przedziału
  14. double c;
  15. const double epsilon = 1e-6;
  16.  
  17. // Metoda bisekcji
  18. while (true)
  19. {
  20. c = (a + b) / 2.0;
  21.  
  22. if (std::fabs(f(c)) < epsilon)
  23. break;
  24.  
  25. if (f(a) * f(c) < 0)
  26. b = c;
  27. else
  28. a = c;
  29. }
  30.  
  31. std::cout << "Miejsce zerowe: x = " << c << std::endl;
  32. std::cout << "f(x) = " << f(c) << std::endl;
  33.  
  34. return 0;
  35. }
  36.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Miejsce zerowe: x = 1.41421
f(x) = 2.68718e-07