fork download
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. double f(double x) {
  6. return x * x * x - x - 2;
  7. }
  8.  
  9. int main() {
  10. double a = 1, b = 2, c;
  11. int iterations = 20;
  12.  
  13. if (f(a) * f(b) >= 0) {
  14. cout << "Invalid interval!" << endl;
  15. return 0;
  16. }
  17.  
  18. for (int i = 0; i < iterations; i++) {
  19. c = (a + b) / 2;
  20. if (f(c) == 0.0) break;
  21. else if (f(a) * f(c) < 0) b = c;
  22. else a = c;
  23. }
  24.  
  25. cout << "Root = " << c << endl;
  26. return 0;
  27. }
  28.  
Success #stdin #stdout 0.01s 5296KB
stdin
Standard input is empty
stdout
Root = 1.52138