fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. double f(double x) {
  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. double x1, x2, x3, f1, f2, f3;
  14. int step = 1;
  15. printf("Enter the value of x1: ");
  16. scanf("%lf", &x1);
  17. printf("Enter the value of x2: ");
  18. scanf("%lf", &x2);
  19.  
  20. printf("\n Iteration\t x1\t x2\t x3\t f(x1)\t f(x2)\n");
  21. printf(" --------------------------------------------------------------------------\n");
  22.  
  23. f1 = f(x1);
  24. f2 = f(x2);
  25.  
  26. do {
  27. x3 = (f2 * x1 - f1 * x2) / (f2 - f1);
  28. f3 = f(x3);
  29. printf("%8d\t%12.6lf\t%10.6lf\t%10.6lf\t%10.6lf\t%10.6lf\n", step, x1, x2, x3, f1, f2);
  30. if (fabs(f3) < 0.00001)
  31. break;
  32. x1 = x2;
  33. f1 = f2;
  34. x2 = x3;
  35. f2 = f3;
  36. step++;
  37. } while (step <= 8);
  38.  
  39. printf(" --------------------------------------------------------------------------\n");
  40. printf("\n Approximate root = %.6lf\n", x3);
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0.01s 5312KB
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