SHARE
TWEET

Untitled

a guest Feb 22nd, 2019 75 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 7. Write a program that will compute statistics for n coin tosses. Ask the user
  2. // for the value of n. You should use rand() to get two random integers: 0 or 1. If
  3. // you get 0, it should count as heads; if you get 1, it should count as tails. The
  4. // program will then display the total number of heads and tails as well as their
  5. // percentages. Use the increment operator "++" to count each h and t that you get.
  6. // To get the two averages you must use a function. Example output:
  7.  
  8. // Enter the number of times to toss a coin: 4
  9. // Tossing!
  10. // You got heads
  11. // You got tails
  12. // You got tails
  13. // You got heads
  14. // Number of heads: 2
  15. // Number of tails: 2
  16. // Percentage of heads: 50%
  17. // Percentage of tails: 50%
  18.  
  19. #include <iostream>
  20. #include <cstdlib>
  21. #include <ctime>
  22.  
  23. using namespace std;
  24.  
  25. double get_average(int x, int total);
  26.  
  27. int main()
  28. {
  29.     srand(time(NULL));
  30.  
  31.     int heads = 0, tails = 0, i = 0, total_tosses = 0;
  32.  
  33.     cout << "Enter the number of times to toss a coin: ";
  34.     cin >> total_tosses;
  35.  
  36.     // This loop simulates a coin toss. It runs 'total_tosses' times. Each time
  37.     // we generate a random number: 0 or 1. If we get 0, we increment 'heads' by
  38.     // one. Else, we increment 'tails' by one.
  39.  
  40.     while (i++ < total_tosses)
  41.     {
  42.         if (rand() % 2 == 0)
  43.             heads++;
  44.         else
  45.             tails++;
  46.     }
  47.  
  48.     // Print the results. Call our 'get_average' to print the average of heads and tails.
  49.  
  50.     cout << "Number of heads: " << heads << endl;
  51.     cout << "Number of tails: " << tails << endl;
  52.     cout << "Percentage of heads: " << get_average(heads, total_tosses) << "%" << endl;
  53.     cout << "Percentage of tails: " << get_average(tails, total_tosses) << "%" << endl;
  54.  
  55.     return 0;
  56. }
  57.  
  58. double get_average(int x, int total)
  59. {
  60.     return ((double)x / total) * 100;
  61. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top