fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. double monte_carlo_e(int n) {
  5. int count = 0;
  6. for (int i = 0; i < n; i++) {
  7. double sum = 0.0;
  8. int k = 0;
  9. while (sum < 1.0) {
  10. sum += (double)rand() / RAND_MAX;
  11. k++;
  12. }
  13. count += k;
  14. }
  15. return (double)count / n;
  16. }
  17.  
  18. int main() {
  19. int n = 1000000; // 試行回数
  20. double e_approx = monte_carlo_e(n);
  21. printf("%f\n", e_approx);
  22. return 0;
  23. }
Success #stdin #stdout 0.06s 5288KB
stdin
Standard input is empty
stdout
2.718689