Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 7. Write a program that will compute statistics for n coin tosses. Ask the user
- // for the value of n. You should use rand() to get two random integers: 0 or 1. If
- // you get 0, it should count as heads; if you get 1, it should count as tails. The
- // program will then display the total number of heads and tails as well as their
- // percentages. Use the increment operator "++" to count each h and t that you get.
- // To get the two averages you must use a function. Example output:
- // Enter the number of times to toss a coin: 4
- // Tossing!
- // You got heads
- // You got tails
- // You got tails
- // You got heads
- // Number of heads: 2
- // Number of tails: 2
- // Percentage of heads: 50%
- // Percentage of tails: 50%
- #include <iostream>
- #include <cstdlib>
- #include <ctime>
- using namespace std;
- double get_average(int x, int total);
- int main()
- {
- srand(time(NULL));
- int heads = 0, tails = 0, i = 0, total_tosses = 0;
- cout << "Enter the number of times to toss a coin: ";
- cin >> total_tosses;
- // This loop simulates a coin toss. It runs 'total_tosses' times. Each time
- // we generate a random number: 0 or 1. If we get 0, we increment 'heads' by
- // one. Else, we increment 'tails' by one.
- while (i++ < total_tosses)
- {
- if (rand() % 2 == 0)
- heads++;
- else
- tails++;
- }
- // Print the results. Call our 'get_average' to print the average of heads and tails.
- cout << "Number of heads: " << heads << endl;
- cout << "Number of tails: " << tails << endl;
- cout << "Percentage of heads: " << get_average(heads, total_tosses) << "%" << endl;
- cout << "Percentage of tails: " << get_average(tails, total_tosses) << "%" << endl;
- return 0;
- }
- double get_average(int x, int total)
- {
- return ((double)x / total) * 100;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement