Hello, I was assigned this program that flips a coin a number of times and displays how many times heads was flipped and how many times tails was flipped.
I finished the program itself, the only problem is that I need to add a function into my program. I am having a hard time understanding the functions and I was wondering if I could get some help from you guys on adding one to this code.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int randNum(); //Prototype Function for the Random Number Generator.
int main()
{
int flip, tosses, x;
int heads = 0;
int tails = 0;
cout << "How many times would you like to toss the coin?" << endl;
cin >> tosses;
srand(time(0)); //Initializes random number seed.
randNum();
cout << "-In " << tosses << " tosses. There were " << heads << " heads and " << tails << " tails.-";
return 0;
}
int randNum() {
for (x = 0; x < tosses; x++) {
flip = rand() % 2 + 1;
if (flip == 2) {
heads++;
}
else {
tails++;
}
}
}
As you can see, I already tried adding a function. It is not turning out so well.
It is true that rand() is a pseudo-random generator and as such returns values from predetermined sequence. However, the call to srand() changes the position within the sequence and thus the question is how the value returned by time(0) does change.
Hello, I still seem to be having a problem. I am just simply trying to call a function that will ask the number of times you want the coin to be flipped and then it returns that value. I must not be doing correctly. Here is the code.
why do you have to use two functions? you could just replace line 16 with 36 and 37.
Code EX:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main()
{
int flip, t, x;
int heads = 0;
int tails = 0;
cout << "How many times would you like to toss the coin?" << endl;
cin >> t;
srand(time(0)); //Initializes random number seed.
for (x = 0; x < t; x++){flip = rand() % 2 + 1;
if(flip == 2){heads++;}else{tails++;}}
cout<<"-In "<<t<<" tosses. There were "<<heads<<" heads and "<<tails<<" tails.-";
return 0;}