fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. double f(double x)
  4. {
  5. double coe[] = {1, 0, -4, -9};
  6. double result = coe[0];
  7. for (int i = 1; i < 4; i++)
  8. result = result * x + coe[i];
  9. return result;
  10. }
  11.  
  12. int main()
  13. {
  14. double x1, x2;
  15. cout << "Enter the value of x1: ";
  16. cin >> x1;
  17. cout << "\nEnter the value of x2: ";
  18. cin >> x2;
  19.  
  20. cout << "\n\n";
  21. cout << " Iteration" << setw(10) << "x1" << setw(12) << "x2"
  22. << setw(12) << "x3" << setw(12) << "f(x1)" << setw(12) << "f(x2)" << endl;
  23. cout << " --------------------------------------------------------------------------\n";
  24.  
  25. double f1 = f(x1);
  26. double f2 = f(x2);
  27. double x3, f3;
  28. int step = 1;
  29.  
  30. do {
  31. x3 = (f2 * x1 - f1 * x2) / (f2 - f1);
  32. f3 = f(x3);
  33.  
  34. cout << setw(8) << step
  35. << setw(14) << fixed << setprecision(6) << x1 << setw(12) << x2 << setw(12) << x3
  36. << setw(12) << f1 << setw(12) << f2 << endl;
  37.  
  38. if (fabs(f3) < 0.00001)
  39. break;
  40.  
  41. x1 = x2;
  42. f1 = f2;
  43. x2 = x3;
  44. f2 = f3;
  45. step++;
  46. } while (step <= 8);
  47.  
  48. cout << " --------------------------------------------------------------------------\n";
  49. cout << "\n Approximate root = " << fixed << setprecision(6) << x3 << endl;
  50. cout << endl;
  51.  
  52. return 0;
  53. }
  54.  
Success #stdin #stdout 0.01s 5280KB
stdin
4
2
stdout
Enter the value of x1: 
Enter the value of x2: 

   Iteration        x1          x2          x3       f(x1)       f(x2)
   --------------------------------------------------------------------------
       1      4.000000    2.000000    2.375000   39.000000   -9.000000
       2      2.000000    2.375000    2.866165   -9.000000   -5.103516
       3      2.375000    2.866165    2.681284   -5.103516    3.080613
       4      2.866165    2.681284    2.704785    3.080613   -0.448618
       5      2.681284    2.704785    2.706548   -0.448618   -0.031298
       6      2.704785    2.706548    2.706528   -0.031298    0.000360
   --------------------------------------------------------------------------

   Approximate root = 2.706528