fork download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. // Definicja funkcji
  7. double f(double x)
  8. {
  9. return x * x * x - x - 2; // f(x) = x^3 - x - 2
  10. }
  11.  
  12. int main()
  13. {
  14. double a, b, c;
  15. double eps = 1e-6;
  16.  
  17. cin >> a >> b;
  18.  
  19. if (f(a) * f(b) >= 0)
  20. {
  21. cout << "Brak miejsca zerowego w przedziale";
  22. return 0;
  23. }
  24.  
  25. while (fabs(b - a) > eps)
  26. {
  27. c = (a + b) / 2;
  28.  
  29. if (f(c) == 0.0)
  30. break;
  31. else if (f(a) * f(c) < 0)
  32. b = c;
  33. else
  34. a = c;
  35. }
  36.  
  37. cout << c;
  38.  
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0s 5268KB
stdin
1 10
stdout
1.52138