生日悖论C++代码
#include <ctime> #include <iostream> #include <algorithm> using namespace std; class birthday { public: birthday(int n = 10000, int m = 50) : n(n), m(m) {} void test() { srand((unsigned)time(nullptr)); int cnt = 0; for (int i = 0; i < n; ++i) { bool *p = new bool[365]; fill(p, p + 365, false); for (int j = 0; j < m; ++i) { auto x = rand() % 365; if (p[x]) break; else { p[x] = true; cnt++; } } delete[] p; } cout << cnt * 1.0 / n << endl; } private: int n; //实验次数 int m; //人数 }; int main() { birthday a; a.test(); return 0; }