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