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