fork download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. double trapezy(double a, double b, int n)
  7. {
  8. double h = (b - a) / n;
  9. double suma = 0.0;
  10.  
  11. // suma wartości wewnętrznych
  12. for (int i = 1; i < n; i++)
  13. {
  14. double x = a + i * h;
  15. suma += sin(x);
  16. }
  17.  
  18. // wzór metody trapezów
  19. suma = (sin(a) + sin(b)) / 2 + suma;
  20. return suma * h;
  21. }
  22.  
  23. int main()
  24. {
  25. double a1 = 0.0, b1 = 3.14;
  26. double a2 = 0.0, b2 = 3.14;
  27. int n1 = 10, n2 = 100;
  28.  
  29. double s1 = trapezy(a1, b1, n1);
  30. double s2 = trapezy(a2, b2, n2);
  31.  
  32. cout << "s1 (n = 10) = " << s1 << endl;
  33. cout << "s2 (n = 100) = " << s2 << endl;
  34.  
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
s1 (n = 10)  = 1.98354
s2 (n = 100) = 1.99983