fork download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. // funkcja f(x)
  7. double f(double x)
  8. {
  9. return sin(x);
  10. }
  11.  
  12. // metoda prostokątów (lewe prostokąty)
  13. double metodaProstokatow(double a, double b, int n)
  14. {
  15. double dx = (b - a) / n;
  16. double x = a;
  17. double S = 0.0;
  18.  
  19. for (int i = 1; i <= n; i++)
  20. {
  21. S += dx * f(x);
  22. x += dx;
  23. }
  24.  
  25. return S;
  26. }
  27.  
  28. int main()
  29. {
  30. double a = 1.0;
  31. double b = 3.0;
  32.  
  33. int N1 = 10;
  34. int N2 = 100;
  35.  
  36. double S1 = metodaProstokatow(a, b, N1);
  37. double S2 = metodaProstokatow(a, b, N2);
  38.  
  39. cout << "f(x) = sin(x)" << endl;
  40. cout << "Przedzial [1, 3]" << endl;
  41.  
  42. cout << "N1 = " << N1 << " S1 = " << S1 << endl;
  43. cout << "N2 = " << N2 << " S2 = " << S2 << endl;
  44.  
  45. return 0;
  46. }
  47.  
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
f(x) = sin(x)
Przedzial [1, 3]
N1 = 10  S1 = 1.59523
N2 = 100  S2 = 1.53725