I think your first post was actually closer. Some questions about that code. Read these questions and look at your code.
Don't get frustrated if you can't answer the questions, keep reading below.
Line 20: what is i? Be specific. Now look at line 36. Why are you incrementing i here?
Line 30: What exactly does payoff() do? What does it return? You're printing whatever it returns here. Why?
Line 35. This will print the last choice, but you already printed it once at line 30.
Line 37. What's going on here? What are you trying to do?
In payOff():
Line 49: What is the purpose of this loop?
Line 52: This prints the payoff, but you print the return value of the payoff at lines 30 & 37. Who is actually supposed to print the payoff?
There isn't a good answer to most of my questions. Much of the code just doesn't do what it needs to do. It's very close, but not quite right.
When programming, you have to be very precise. You need to be clear in own mind what you're trying to accomplish. Then you need to write code to accomplish it. I strongly urge you to write comments in the code that say what the code is supposed to do. In theory, you should be able to read the comments and convince yourself that your algorithm will work. Comment your functions to say what they do and what they return. This would help avoid the ambiguity about payOff().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int randomNum(int num);
int
main()
{
int num = 0;
int totalWinnings = 0;
string choice = "";
double average;
srand(time(0)); // seed the randon number generator
// Play the game 10 times.
for (int plays = 1; plays <= 10; ++plays) {
//
// The code below is for one play of the game
//
int flips = 0; // the number of times we flip the coin
do {
// Get a random number 1-2 in num. Then set "choice"
// to "H" for 1 and "T" for 2.
num = randomNum(num);
if (num == 1)
choice = "H";
else
choice = "T";
++flips; // increment flips
// Print the result of this flip. Note that there's no
// newline so each time through the loop we'll print H or T
// right next to the last one.
cout << choice;
} while (choice != "H"); // the game ends when you get a Heads
int winnings = pow(2, flips); // winnings for this game are 2^n
// print the payoff for this game. Note that it's on the same line
// as the H/T printouts.
cout << " payoff is $" << winnings << '\n';
// Increment the total winnings
totalWinnings += winnings;
}
// Average payout is the total / the number of plays.
// Express the # of plays to a double so the result is a double
average = totalWinnings / 10.0;
cout << "The average payout was $" << average << endl;
return 0;
}
// Return a random number 1 or 2
int
randomNum(int num)
{
num = 1 + rand() % 2;
return num;
}
|