fork download
  1. #include <iostream>
  2. #include <cmath>
  3. #include <functional>
  4. #include <iomanip>
  5. using namespace std;
  6.  
  7. bool correct = false;
  8. double solve(function<double (double)> f, double a, double b, double eps)
  9. {
  10. if (a > b) swap(a, b);
  11. while(fabs(a - b) > eps && (correct = f(a)*f(b) < 0)) {
  12. double x = (a + b) / 2.0;
  13. if ( f(a) * f(x) < 0 )
  14. b = x;
  15. else a = x;
  16. }
  17. return (a + b) / 2.0;
  18. }
  19.  
  20. int main()
  21. {
  22. /*auto f1 = [](double x)->double { return 2 * pow(x, 2.0) - pow(0.5, x) - 3; };*/
  23. auto f1 = [](double x)->double { return x*x - 0.5; };
  24. cout <<"[2;3] : "<<fixed << setprecision(11) << solve( f1, 2, 3, 0.001 );
  25. if(correct)
  26. cout<<" correct";
  27. else
  28. cout<<" incorrect";
  29. cout <<"[0;1] : "<<fixed << setprecision(11) << solve( f1,0, 1, 0.001 );
  30. if(correct)
  31. cout<<" correct";
  32. else
  33. cout<<" incorrect";
  34. cin.get();
  35. return 0;
  36. }
Success #stdin #stdout 0s 2992KB
stdin
Standard input is empty
stdout
[2;3] : 2.50000000000 incorrect[0;1] : 0.70751953125 correct