fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5.  
  6. double a = 1, b = 2, c, eps = 1e-9;
  7. int cnt = 0;
  8.  
  9. while (b - a > eps) {
  10.  
  11. cnt++;
  12. c = (a + b) / 2;
  13.  
  14. double fa = a * a * a - a - 2;
  15. double fc = c * c * c - c - 2;
  16. double fb = b * b * b - b - 2;
  17.  
  18. // if ((fa > 0 && fc < 0) || (fa < 0 && fc > 0))
  19. if (fa * fc < 0) {
  20. b = c;
  21. } else {
  22. a = c;
  23. }
  24.  
  25. }
  26.  
  27. cout << "root ~ " << c << endl;
  28. double error = c * c * c - c - 2;
  29. cout << "error = " << error << endl;
  30. cout << "iterations = " << cnt << endl;
  31.  
  32. return 0;
  33.  
  34. }
Success #stdin #stdout 0s 4520KB
stdin
Standard input is empty
stdout
root ~ 1.52138
error = -2.10862e-09
iterations = 30