fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4.  
  5. using namespace std;
  6.  
  7. int main() {
  8.  
  9. int N = 100000; // N: 抽樣的數量
  10. int m = 0; // M: 落在四分之一圓的點數
  11. for (int i = 1; i <= N; i++) {
  12.  
  13. double x = (double) rand() / RAND_MAX;
  14. double y = (double) rand() / RAND_MAX;
  15.  
  16. if (x * x + y * y < 1) {
  17. m++; //若該點落在四分之一內則 M++
  18. }
  19.  
  20. }
  21. cout << "pi~ " << 4.0 * m / N << endl;
  22. return 0;
  23. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
pi~ 3.14152