fork download
  1. /* rand example: guess the number */
  2. #include <stdio.h> /* printf, scanf, puts, NULL */
  3. #include <stdlib.h> /* srand, rand */
  4. #include <math.h>
  5.  
  6. unsigned Rand()
  7. {
  8. // 利用 y = 5000*(sin((x-0.5)*π)+1) 產生亂數, x = [0~1];
  9.  
  10. double x = ((double)rand())/RAND_MAX;
  11.  
  12. unsigned y = (unsigned)((sin((2*x-0.5)*M_PI)+1)*5000); // y = [0~10000)
  13.  
  14. if(y >= 10000) return Rand(); // 確保亂數值在 [0~10000)之間
  15. return y;
  16. }
  17.  
  18. int main(int argc, char *argv[])
  19. {
  20. unsigned count[10] = {0,0,0,0,0,0,0,0,0,0}; // 亂數在該區間出現次數
  21. // count[0] = [0~1000)
  22. // count[1] = [1000~2000)
  23. // ...
  24. // count[9] = [9000~10000)
  25.  
  26. // 產生一萬次亂數,並記錄亂數在某區間出現個數
  27. for(unsigned i = 0 ; i < 10000u ; ++i)
  28. {
  29. ++count[Rand()/1000];
  30. }
  31.  
  32. // 顯示結果
  33. for(unsigned i = 0 ; i < 10u ; ++i)
  34. {
  35. printf("[%05u~%05u) 出現 %u 次\n", i*1000 , (i+1)*1000 , count[i]);
  36. }
  37.  
  38. return EXIT_SUCCESS;
  39. }
  40.  
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
[00000~01000) 出現 2041 次
[01000~02000) 出現 904 次
[02000~03000) 出現 764 次
[03000~04000) 出現 621 次
[04000~05000) 出現 634 次
[05000~06000) 出現 635 次
[06000~07000) 出現 682 次
[07000~08000) 出現 767 次
[08000~09000) 出現 882 次
[09000~10000) 出現 2070 次