fork download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. // funkcja f(x) = sqrt(1 - x^2)
  7. double f(double x) {
  8. return sqrt(1.0 - x * x);
  9. }
  10.  
  11. int main() {
  12. int n;
  13. cout << "Podaj liczbe podprzedzialow: ";
  14. cin >> n;
  15.  
  16. double a = -1.0;
  17. double b = 1.0;
  18. double h = (b - a) / n;
  19.  
  20. double suma_prostokaty = 0.0;
  21. double suma_trapezy = 0.0;
  22.  
  23. // --- Metoda prostokatow (srodki przedzialow) ---
  24. for (int i = 0; i < n; i++) {
  25. double x = a + (i + 0.5) * h; // srodek przedzialu
  26. suma_prostokaty += f(x);
  27. }
  28. double wynik_prostokaty = 2.0 * h * suma_prostokaty;
  29.  
  30. // --- Metoda trapezow ---
  31. suma_trapezy = (f(a) + f(b)) / 2.0;
  32. for (int i = 1; i < n; i++) {
  33. double x = a + i * h;
  34. suma_trapezy += f(x);
  35. }
  36. double wynik_trapezy = 2.0 * h * suma_trapezy;
  37.  
  38. cout << "Przyblizenie PI (metoda prostokatow): "
  39. << wynik_prostokaty << endl;
  40.  
  41. cout << "Przyblizenie PI (metoda trapezow): "
  42. << wynik_trapezy << endl;
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0.01s 5316KB
stdin
Standard input is empty
stdout
Podaj liczbe podprzedzialow: Przyblizenie PI (metoda prostokatow): 3.14159
Przyblizenie PI (metoda trapezow): 3.14159