C++ Writing simple coin flip game - c++

I'm writing a code for a game that prompts the user to pick how many times they want to flip a coin and guess how many times it will land on heads. I wrote most of, just need help finishing it up. I tried to include a count of the heads but ran into problems.
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
int myRandNumGen(){
int num = rand();
return num;
}
char coinTossFunction( ){
char coinToss;
int coinTossValue = (myRandNumGen()%2); // 0 or 1
switch (coinTossValue) {
case 0:
coinToss = 'H';
break;
case 1:
coinToss = 'T';
break;
default:
break;
}
return coinToss;
}
int calcCoin(int n){
int cout_heads=0;
for(int i=0;i<=n;i++){
if(coinTossFunction() == 'H')
++cout_heads;
}
return (cout_heads/n);
}
int main(){
int coinflips, guess;
cout << "How many times do you want to flip the coin? " << endl;
cin >> coinflips;
cout << "Guess how many times a coin will land on heads if flipped: " << endl;
cin >> guess;
if (guess>coinflips) {
cout << "Guess Error";
}
for(int i=1;i<=coinflips;i++){
cout << calcCoin;
}

Here are a few problems with your code:
for(int i=0;i<=n;i++)
This will make i take the values from 0 to n, which means you will enter in the loop n+1 times, instead of n times.
return (cout_heads/n);
Since both variables cout_headsand n are integers, this will perform an integer division, and not a floating point division. The result will always be 0 or 1 in this case.
cout << calcCoin;
When you call a function you need to put parenthesis. Also your calCoin function takes a parameter.

Related

C++ Coin Toss Confusion

So for my class assignment I was told to make a coin toss program but in a different fashion than those I found online.
The goal of our lab was to create a coin toss program in which it will run 4 different times and it will "succeed" if it gets 4 heads or 4 tails. If it fails (ie. 2 tails 2 heads) then it will keep trying until it gets that 4 heads or 4 tails.
So far I have
#include <iostream>
#include <cstdlib>
using namespace std;
enum coinFace { head , tail };
void coinToss()
{
for (int flips = 1; flips <= 4; flips++)
{
int result = rand() % 3;
if (result == 1)
cout << "Heads" << endl;
else
cout << "Tails" << endl;
}
}
int main()
{
unsigned seed;
int trials;
cout << "Please enter the seed." << endl;
cin >> seed;
cout << "How many trials would you like?" << endl;
cin >> trials;
srand(seed);
coinToss();
return 0;
}
I'm very lost at this point. I don't understand how to use the enum fuction and I don't really know how to... continue from here.
http://imgur.com/Rt3Lf9l This is the post to the assignment. I want to be able to learn instead of simply receiving the answer please! But I don't know how to go on from here so I'm most likely going to need lots of help. Thank you in advance.
Because you only need to store the state of head/tail, you can use enum or what ever. What you need to add are followings: 1) Count the times of head/tail. 2) Judge fail/success.

How to take numerous inputs without assigning variable to each of them in C++?

I'm beginning with C++. The question is: to write a program to input 20 natural numbers and output the total number of odd numbers inputted using while loop.
Although the logic behind this is quite simple, i.e. to check whether the number is divisible by 2 or not. If no, then it is an odd number.
But, what bothers me is, do I have to specifically assign 20 variables for the user to input 20 numbers?
So, instead of writing cin>>a>>b>>c>>d>>.. 20 variables, can something be done to reduce all this calling of 20 variables, and in cases like accepting 50 numbers?
Q. Count total no of odd integer.
A.
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n,odd=0;
cout<<"Number of input's\n";
cin>>n;
while(n-->0)
{
int y;
cin>>y;
if(y &1)
{
odd+=1;
}
}
cout<<"Odd numbers are "<<odd;
return 0;
}
You can process the input number one by one.
int i = 0; // variable for loop control
int num_of_odds = 0; // variable for output
while (i < 20) {
int a;
cin >> a;
if (a % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
If you do really want to save all the input numbers, you can use an array.
int i = 0; // variable for loop control
int a[20]; // array to store all the numbers
int num_of_odds = 0; // variable for output
while (i < 20) {
cin >> a[i];
i++;
}
i = 0;
while (i < 20) {
if (a[i] % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
Actually, you can also combine the two while-loop just like the first example.
Take one input and then process it and then after take another intput and so on.
int n= 20; // number of input
int oddnum= 0; //number of odd number
int input;
for (int i = 0; i < n; i ++){
cin >> input;
if (input % 2 == 1) oddnum++;
}
cout << "Number of odd numbers :"<<oddnum << "\n";

Why are my if statements not working consistently?

I'm making a coin toss program for my c++ class and we are required to make a function that flips a coin and prints out if it is heads or tails, and print 10 per line. When I ran the program though the if statements I used to detect if the coin was heads or tails weren't enough to pick from the two.
#include <iostream>
#include <ctime>
using namespace std;
void coinToss(int times);
int main()
{
srand(time(0));
int times;
cout << "How many times would you like to toss the coin?" << endl;
cin >> times;
coinToss(times);
return 0;
}
void coinToss(int times)
{
int toss = 0, count = 0;
for(int i = 0; i < times;i++)
{
toss = rand()%2;
if(toss == 1)//Detects if coin is heads.
{
cout << "H";
}
if(toss == 0)//Detects if coin is tails.
{
cout << "T";
}
else //I had to include this for the program to run, further explanation below the code.
{
cout << "Ya done goofed.";
}
count++; //Counts to ten
if(count == 10) //Skips to the next line if the coin has been tossed ten times.
{
cout << endl;
count = 0;
}
}
}
At one point I replaced the heads or tails with "cout << toss;" and the only numbers returned were 1 and 0. I don't understand how if I'm getting only the two numbers I'm checking for some of them aren't being caught by my if statements.
To complete the assignment I've changed the second if statement into an else statement and everything seems peachy, but I'd really like to understand what's going on here.
What happens with your code is:
Is the result 1 ? Then print H. Keep going. Is the result 0 ? Then print T. Else, if it's not 0, print "Ya done goofed.".
You need to keep your if statements linked together:
if (toss == 1) {
cout << "H";
} else if (toss == 0) {
cout << "T";
} else {
cout << "Ya done goofed.";
}
You won't fall in the else case anymore and will be able to remove it.
As a sidenote, regarding your overall program structure: your coinToss function shouldn't do everything. Your code should be more splitted: a function which returns H or T, a function which calls this function X times as requested by the user and formatting the output would be a good start.
Another small note: your count variable, allowing you to add a new line every 10 flips, could be removed. i % 10 will give you the same result: every ten increments, i % 10 would be equal to 0.
You're probably printing the output properly, then terminating without writing a newline on the last line, and your shell prompts clearing back to the left margin and overwriting your output (clearing the rest of the line to boot). If you have less than 10 tosses, your only line of output may appear lost, otherwise it'll be the last line.
Try adding an extra std::cout << '\n'; before main returns.
(Separately, you can say std::cout << "HT"[rand() % 2];, or std::cout << (rand() % 2 ? 'H' : 'T'); and do away with the ifs, but it's no big deal... whatever's clearest for you at this stage)
Well, rand()%2 will produce only two numbers: 1 and 0, this seems to be in line with your task as a coin is a boolean number generator, isn't it? :)
Therefore this seems to do the job you are looking for:
#include <iostream>
#include <ctime>
using namespace std;
void coinToss(int times);
int main()
{
srand(time(0));
int times;
cout << "How many times would you like to toss the coin?" << endl;
cin >> times;
coinToss(times);
return 0;
}
void coinToss(int times)
{
int toss = 0, Count = 0;
for(int i = 0; i < times;i++)
{
toss = rand() % 2;
// Choose:
cout << ((toss) ? "H" : "T"); // if you want a character
// or
cout << toss; // if you want the number
Count++; //Counts to ten
if(Count == 10) //Skips to the next line if the coin has been tossed ten times.
{
cout << endl;
Count = 0;
}
}
}
if(toss == 1)//Detects if coin is heads.
{
cout << "H";
}
else if(toss == 0)//Detects if coin is tails.
{
cout << "T";
}
You need to use else-if statement. You also need not use else after the toss==0 because rand()%2 will either be 0 or 1. There is no third option.
rand() returns a pseudo-random integral number in the range between 0 and RAND_MAX. And, rand() % 2 will be 0 or 1. So, there would be:
if(toss == 1)//Detects if head
{
cout << "H";
}
else // tail
{
cout << "T";
}
I don't think there is anything wrong with this. Well not that I can see... If I add some debug then I see what I think you're expecting...
#include <iostream>
#include <ctime>
using namespace std;
void coinToss(int times);
int main() {
srand(time(0));
int times;
cout << "How many times would you like to toss the coin?" << endl;
cin >> times;
coinToss(times);
return 0;
}
void coinToss(int times) {
int toss = 0, count = 0;
for(int i = 0; i < times;i++) {
toss = rand() % 2;
cout << "Toss: " << toss << endl;
if(toss == 1)//Detects if coin is heads.
{
cout << "H (" << toss << ")" << endl;
}
if(toss == 0)//Detects if coin is tails.
{
cout << "T (" << toss << ")" << endl;
}
count++; //Counts to ten
if(count == 10) //Skips to the next line if the coin has been tossed ten times.
{
//cout << endl; count = 0;
}
}
}
And compile it
g++ coin_toss.cc
And run it
./a.out
How many times would you like to toss the coin?
4
Toss: 1
H (1)
Toss: 0
T (0)
Toss: 0
T (0)
Toss: 0
T (0)
Then this is exactly what I expect or am I missing something?
You don't need an "if else if" statement.
You can also use a switch:
switch( rand() % 2 )
{
case 0:
cout << "T";
break;
case 1:
cout << "H";
break;
default:
cout << "oops you goofed!;
}
// continue within for loop
If you "forgot" the break after case 1 you would again get the "oops you goofed!" message after each head toss.

Is there a way to not include a negative number in an average, when entering a negative number is how you terminate the program?

Sorry about last time for those who saw my previous thread. It was riddled with careless errors and typos. This is my assignment:
"Write a program that will enable the user to enter a series of non-negative numbers via an input statement. At the end of the input process, the program will display: the number of odd numbers and their average; the number of even numbers and their average; the total number of numbers entered. Enable the input process to stop by entering a negative value. Make sure that the user is advised of this ending condition."
And here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number, total1=0, total2=0, count1=0, count2=0;
do
{
cout << "Please enter a number. The program will add up the odd and even ones separately, and average them: ";
cin >> number;
if(number % 2 == 0)
{
count1++;
total1+=number;
}
else if (number >= 0)
{
count2++;
total2+=number;
}
}
while (number>=0);
int avg1 = total1/count1;
int avg2 = total2/count2;
cout << "The average of your odd numbers are: " << avg1 << endl;
cout << "The average of your even numbers are " << avg2 << endl;
}
It seems to be working fine, but when I enter a negative number to terminate the program, it includes it with the rest of the averaged numbers. Any advice to get around this? I know it's possible, but the idea escapes me.
Your main loop should be like this:
#include <iostream>
for (int n; std::cout << "Enter a number: " && std::cin >> n && n >= 0; )
{
// process n
}
Or, if you want to emit a diagnostic:
for (int n; ; )
{
std::cout << "Enter a number: ";
if (!(std::cin >> n)) { std::cout << "Goodbye!\n"; break; }
if (n < 0) { std::cout << "Non-positve number!\n"; break; }
// process n
}
After here:
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
Immediately check if the number is negative
if(number < 0) break;
Now you wouldn't need to use your do-while loop in checking if the number is negative. Thus, you can use an infinite loop:
while(true) {
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
if(number < 0) break;
// The rest of the code...
}
ADDITIONAL:
There is something wrong in your code. You aren't showing the user how much the number of even and odd numbers are, and the total number of numbers entered.
ANOTHER ADDITIONAL: You should use more meaningful variable names:
int totalNumEntered = 0, sumEven = 0, sumOdd = 0, numEven = 0, numOdd = 0;
Of course I am not limiting you to these names. You can also use other similar names.
FOR THE INTEGER DIVISION PROBLEM:
You must cast your expression values to the proper type (in this case, it is float). You should also change the averages variables' types to float:
float avg1 = float(total1) / float(count1);
float avg2 = float(total2) / float(count2);
Immediately after cin >> number, check for < 0, and break if so. Try to step through the program line by line to get a feel for the flow of execution. Have fun learning, and good luck!

Getting a 2D array from a function that returns an int c++

I have an assignment that simulates a dice game. As part of the program, the user enters the number of dice to roll and the number of times to roll them. If the user rolls 4 dice, the program should sum the 4 values, store the result in an array, then redo the program the number times defined by the user. The main code and the function prototypes were defined by our tutor and cannot be amended. We have to write the function.
In Step 3 of the main, there are two for loops. The inner for loop calls the function in question. A 2D array rollSums[][] is assigned to the result of the function. This array is to be used in another function. I can't figure out how to populate the 2D array correctly from the function. The code and my attempt at the function is below:
#include <iostream>
#include <iomanip>
#include <cstdlib> // needed for functions srand() and rand()
#include <ctime> // needed for function time()
#include <cmath> // needed for sqrt()
using namespace std;
const int MAXNUMTOROLL=10;
const int MAXROLLS=100;
int rollDice(int diceVals[], int numToRoll);
int main()
{
int sum;
int rollSums[MAXNUMTOROLL][MAXROLLS];
int diceVals[MAXROLLS];
double mean[MAXNUMTOROLL], std[MAXNUMTOROLL];
int numToRoll, numRolls;
srand(time(NULL));
// STEP 1: Ask user to input the maximum number of dice to use:
cout << "Please enter the maximum number of dice to use:" << endl;
do
{
cin >> numToRoll;
} while (numToRoll < 0 || numToRoll > MAXNUMTOROLL);
cout << "Please enter the number of rolls:" << endl;
// STEP 2: Ask user to input the number of rolls to carry out:
do
{
cin >> numRolls;
} while (numRolls < 0 || numRolls > MAXROLLS);
// STEP 3: For k=1 to numToRoll, simulated numRolls rolls of the dice
// and store the sum of the numbers rolled in the array rollSums[][]
for (int k=1;k<=numToRoll;k++)
{
for (int i=0;i<numRolls;i++)
{
rollSums[k-1][i] = rollDice(diceVals, k);
}
}
return 0;
}
int rollDice(int diceVals[], int numToRoll) //function simulating throwing of dice
{
int sum=0;
int i=0;
for(i=0;i<numToRoll;i++)
{
diceVals[i]=1+rand()%6;
sum=sum+diceVals[i];
}
return sum;
}
adohertyd, see my comments in the code sample:
#include <iostream>
#include <iomanip>
#include <cstdlib> // needed for functions srand() and rand()
#include <ctime> // needed for function time()
#include <cmath> // needed for sqrt()
using namespace std;
const int MAXNUMTOROLL=10;
const int MAXROLLS=100;
const bool show_debug = true;
int rollDice(int diceVals[], int numToRoll);
int main()
{
int roll_Sums[MAXNUMTOROLL];
int diceVals[MAXROLLS];
//double mean[MAXNUMTOROLL], std[MAXNUMTOROLL];
int numDice, numThrows;
//Initialize random number generator with the current time
srand(time(NULL));
// STEP 1: Ask user to input the maximum number of dice to use:
cout << "Please enter the maximum number of dice to use:" << endl;
// STEP 2: Validate number of dice input
do
{
cin >> numDice;
} while (numDice < 0 || numDice > MAXNUMTOROLL);
//STEP 3: Ask user to input the number of times to throw each dice
cout << "Please enter the number of rolls:" << endl;
// STEP 4: Validate number of throws input
do
{
cin >> numThrows;
} while (numThrows < 0 || numThrows > MAXROLLS);
cout << "\n\nThrowing Dice Now...\n\n";
// STEP 5: Roll the dice
//The loop deals with each dice
for (int diceCount = 0; diceCount < numDice; diceCount++)
{
//The function call deals with all the throws per dice
//Note: roll_Sums array didn't need to be two dimensional,
// also, rollDice gets passed diceVals[] by value and the number of throws to execute
roll_Sums[diceCount] = rollDice(diceVals, numThrows);
//Debug output
if(show_debug)
{
//Since roll_Sums is zero based, add one to the visible index so the user doesn't get confused :P
cout << "Roll Sum for dice #" << diceCount + 1 << ": " << roll_Sums[diceCount] << endl << endl;
}
}
return 0;
}
//rollDice() returns the sum of all the dice rolls it performed
int rollDice(int diceVals[], int numToRoll)
{
int sum=0;
for(int i=0;i<numToRoll;i++)
{
//Get your random dice rolls
diceVals[i]=1+rand()%6;
//Debug output
if(show_debug)
{
cout << "Dice Roll # " << i+1 << ": " << diceVals[i] << endl;
}
//Accumulate your value, e.g. "sum"
sum += diceVals[i];
}
return sum;
}