fork download
  1. // estimating the PI using Monte Carlo Simulation in C
  2. #include<stdio.h>
  3. #include<math.h>
  4. #include<stdlib.h>
  5. #include<time.h>
  6. #define SEED time(NULL)
  7. int main(){
  8. srand( SEED );
  9. int i, count, n;
  10. double x,y,z,p1;
  11. printf("n = ");
  12. scanf("%d", &n);
  13. count = 0;
  14. for(i=0; i<n; i++){
  15. x=(double)rand()/RAND_MAX;
  16. y=(double)rand()/RAND_MAX;
  17. z=x*x+y*y;
  18. if(z<=1){
  19. count++;
  20. }
  21. }
  22. p1=(double)count/n*4;
  23. printf("Approximate PI = %g", p1);
  24. return 0;
  25. }
Success #stdin #stdout 0.01s 5288KB
stdin
8
stdout
n = Approximate PI = 3