Hello, so for my homework i am supposed to create a coin toss stimulator. The output should should the number of flips the user chose to enter, number of heads and tails and the percentage. Here is my code below, i cannot get the number of heads and tails to be right, everytime i test it out, the number of heads and tails becomes 0, which makes the percentage 0 as well. please help! thanks!
Try something like this. You don't need to use srand() before getting each next value. It only uses to initialize PRN-generator before start current sequence of numbers.
a) If you divide an integer by an other integer, you’re performing an integer division.
It means it returns an integer, i.e. a number which can be 0 or 1 but not between 0 and 1. If the result is between 0 and 1, it will become 0.
b) ‘final’ is a reserved word. You can’t have a variable named ‘final’.
c) Declaring variables just before using them is better than declaring them all together at the beginning of a function.
#include <cstdlib>
#include <ctime>
#include <iostream>
int coinToss();
int main()
{
srand(time(0));
char quit {};
std::cout << "Hello and welcome to the Coin Toss Stimulator.\n";
do {
int flips = 0;
do {
std::cout << "How many times do you wish to flip the coin? ";
std::cin >> flips;
if (flips <= 0) {
std::cout << "Please enter a number greater than 0.\n";
}
} while(flips < 1);
constexprint HEAD = 1;
int total = 0,
totalHeads = 0,
totalTails = 0;
while (flips > total)
{
int chance = coinToss();
if (chance == HEAD) {
totalHeads++;
} else {
totalTails++;
}
total++;
}
// calculations for percent
double percentHeads = static_cast<double>(totalHeads) / flips,
percentTails = static_cast<double>(totalTails) / flips;
//stats
std::cout << "\nCoin Toss Statistics""\n_____________________""\nNumber of coin tosses: " << flips
<< "\nNumber of heads: " << totalHeads
<< "\nPercentage of heads: " << percentHeads * 100 << '%'
<< "\nNumber of tails: " << totalTails
<< "\nPercentage of tails: " << percentTails * 100 << "%\n";
//Asks if they would like to run the program again
std::cout << "If you would wish to end this program, press Q. ";
std::cin >> quit;
} while (quit != 'q' && quit != 'Q');
return 0;
}
int coinToss()
{
int toss = rand() % 2 ; // if even returns 0, otherwise returns 1
return toss;
}