fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4. #include <cmath>
  5. using namespace std;
  6.  
  7. int main() {
  8. srand(time(0));
  9. int N[] = {1000, 10000, 100000};
  10.  
  11. for (int n : N) {
  12. int inside = 0;
  13. for (int i = 0; i < n; i++) {
  14. double x = (double) rand() / RAND_MAX;
  15. double y = (double) rand() / RAND_MAX;
  16. if (x*x + y*y <= 1) inside++;
  17. }
  18. double pi = 4.0 * inside / n;
  19. cout << "N=" << n << " --> π ≈ " << pi
  20. << " , Error = " << fabs(M_PI - pi) << endl;
  21. }
  22. return 0;
  23. }
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
N=1000 --> π ≈ 3.2 , Error = 0.0584073
N=10000 --> π ≈ 3.1296 , Error = 0.0119927
N=100000 --> π ≈ 3.1334 , Error = 0.00819265