fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <time.h>
  5.  
  6. #define PI 3.14159265358979323846
  7.  
  8. int main(void)
  9. {
  10. long long N;
  11. printf("点の数を入力してください: ");
  12. scanf("%lld", &N);
  13.  
  14. long long count = 0;
  15. srand(time(NULL));
  16.  
  17. for(long long i = 0; i < N; i++)
  18. {
  19. double x = (double)rand() / RAND_MAX;
  20. double y = (double)rand() / RAND_MAX;
  21.  
  22. if(x*x + y*y <= 1.0)
  23. count++;
  24. }
  25.  
  26. double pi = 4.0 * count / N;
  27. double error = fabs(pi - PI) / PI;
  28.  
  29. printf("近似値: %.10f\n", pi);
  30. printf("誤差率: %.10f\n", error);
  31.  
  32. return 0;
  33. }
Success #stdin #stdout 0.03s 5308KB
stdin
1000000
stdout
点の数を入力してください: 近似値: 3.1410120000
誤差率: 0.0001848278