1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { // Initialize random seed srand(static_cast<unsigned>(time(0))); // Simulate coin toss int toss = rand() % 2; // Random number: 0 or 1 // Output result if (toss == 0) { cout << "Result: Heads" << endl; } else { cout << "Result: Tails" << endl; } return 0; } |
Explanation
- Headers:
<iostream>
: For input and output operations.<cstdlib>
: Forrand()
andsrand()
functions.<ctime>
: Fortime()
function to seed the random number generator.
- Main Function:
- Initialize Random Seed:
srand(static_cast<unsigned>(time(0)));
: Seeds the random number generator with the current time. This ensures different random sequences each time the program is run.
- Simulate Coin Toss:
int toss = rand() % 2;
: Generates a random number, either 0 or 1. The% 2
operation limits the range to 0 and 1, simulating two possible outcomes for the coin toss.
- Output Result:
- Checks the value of
toss
. If it is 0, it outputs “Heads”; if it is 1, it outputs “Tails”.
- Checks the value of
- Initialize Random Seed:
Notes:
- Randomness: The
rand()
function generates pseudo-random numbers. By seeding withtime(0)
, the sequence of numbers is different each time the program is run. - Simplified Simulation: This basic simulation does not account for the physics of coin tossing but uses random number generation to simulate the 50/50 chance of heads or tails.