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