fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. float f(float x)
  4. {
  5. return 2*x*x*x + 3*x -1;
  6. }
  7.  
  8. int main() {
  9. float a, b, x, c , d;
  10. float e, f1;
  11.  
  12. cout << "Enter Negative Interval: ";
  13. cin >> a;
  14. cout << "Enter Positive Interval: ";
  15. cin >> b;
  16. cout << "Enter Tolerance: ";
  17. cin >> e;
  18.  
  19. int i = 1;
  20. do {
  21. c = (a + b) / 2;
  22. f1 = f(c);
  23.  
  24. if (f1 > 0)
  25. b = c;
  26. else
  27. a = c;
  28.  
  29. cout << i << ". x = " << c << " f(x) = " << f1 << endl;
  30. i++;
  31. d = b-a;
  32. } while (d >= e);
  33.  
  34. cout << "\nApproximate Root = " << c << endl;
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0.01s 5284KB
stdin
0 1
0.001
stdout
Enter Negative Interval: Enter Positive Interval: Enter Tolerance: 1.  x = 0.5   f(x) = 0.75
2.  x = 0.25   f(x) = -0.21875
3.  x = 0.375   f(x) = 0.230469
4.  x = 0.3125   f(x) = -0.00146484
5.  x = 0.34375   f(x) = 0.112488
6.  x = 0.328125   f(x) = 0.0550308
7.  x = 0.320312   f(x) = 0.0266657
8.  x = 0.316406   f(x) = 0.0125715
9.  x = 0.314453   f(x) = 0.00554609
10.  x = 0.313477   f(x) = 0.00203884

Approximate Root = 0.313477