C++ rand()
Simulate tossing a coin many times
#include <iostream> #include <cmath> #include <ctime> using namespace std; int main()// ww w. ja v a2 s.c om { const int NUMTOSSES = 1000; int heads = 0; // initialize heads count int tails = 0; // initialize tails count int i; double flip, perheads, pertails; srand(time(NULL)); for (i = 1; i <= NUMTOSSES; i++) { flip = double (rand())/RAND_MAX; // scale the number between 0 and 1 if (flip > 0.5) heads = heads + 1; else tails = tails + 1; } perheads = (heads / double (NUMTOSSES)) * 100.0; pertails = (tails / double (NUMTOSSES)) * 100.0; cout << "\nHeads came up " << perheads << " percent of the time"; cout << "\nTails came up " << pertails << " percent of the time" << endl; return 0; }