fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cmath>
  4. using namespace std;
  5.  
  6. // Function definition
  7. double f(double x) {
  8. return 2 * x * x * x + 3 * x - 1;
  9. }
  10.  
  11. int main() {
  12. double x1, x2, x0, f1, f2, f0;
  13. double E = 1e-8;
  14. int i = 0;
  15.  
  16. cout << "Enter the value of x0: ";
  17. cin >> x1;
  18. cout << "\nEnter the value of x1: ";
  19. cin >> x2;
  20.  
  21. f1 = f(x1);
  22. f2 = f(x2);
  23.  
  24. if (f1 * f2 > 0) {
  25. cout << "\nInvalid interval. f(x0) and f(x1) must have opposite signs.\n";
  26. return 0;
  27. }
  28.  
  29. cout << "\n-------------------------------------------------------------";
  30. cout << "\nIteration\t x0\t\t x1\t\t x2\t\t f0\t\t f1\t\t f2";
  31. cout << "\n-------------------------------------------------------------\n";
  32.  
  33. do {
  34. i++;
  35. x0 = (x1 + x2) / 2;
  36. f0 = f(x0);
  37.  
  38. cout << fixed << setprecision(6);
  39. cout << setw(3) << i << "\t\t"
  40. << x0 << "\t" << x1 << "\t" << x2 << "\t"
  41. << f0 << "\t" << f1 << "\t" << f2 << endl;
  42.  
  43. if (f1 * f0 < 0) {
  44. x2 = x0;
  45. f2 = f0;
  46. } else {
  47. x1 = x0;
  48. f1 = f0;
  49. }
  50.  
  51. } while (fabs((x2 - x1) / x2) > E);
  52.  
  53. cout << "\nApproximate root = " << x0 << endl;
  54.  
  55. return 0;
  56. }
  57.  
Success #stdin #stdout 0.01s 5288KB
stdin
-1 
-2
stdout
Enter the value of x0: 
Enter the value of x1: 
Invalid interval. f(x0) and f(x1) must have opposite signs.