fork descargar
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. // Definicja funkcji
  7. double f(double x)
  8. {
  9. return sin(x);
  10. }
  11.  
  12. // Funkcja obliczająca całkę metodą trapezów
  13. double trapezy(double a, double b, int n)
  14. {
  15. double h = (b - a) / n;
  16. double suma = 0.0;
  17.  
  18. suma += (f(a) + f(b)) / 2.0;
  19.  
  20. for (int i = 1; i < n; i++)
  21. {
  22. suma += f(a + i * h);
  23. }
  24.  
  25. return suma * h;
  26. }
  27.  
  28. int main()
  29. {
  30. double a = 0.0;
  31. double b = 3.14;
  32.  
  33. int n1 = 10;
  34. int n2 = 100;
  35.  
  36. double s1 = trapezy(a, b, n1);
  37. double s2 = trapezy(a, b, n2);
  38.  
  39. cout << "s1 (n = 10) = " << s1 << endl;
  40. cout << "s2 (n = 100) = " << s2 << endl;
  41.  
  42. return 0;
  43. }
  44.  
Éxito #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
s1 (n = 10)  = 1.98354
s2 (n = 100) = 1.99983