C++ help! ** Write a function named percentHeads that takes an integer number of
ID: 3668847 • Letter: C
Question
C++ help!
** Write a function named percentHeads that takes an integer number of coin tosses as a parameter and then returns the percentage of times the coin lands on heads when throwing the coin that many times. Represent heads as a 0, and tails as a 1.
Seed your random number generator with srand(4444).
Also, it says I have to test that percentHeads and percentHeads(6) returns correct value. **
Here is an example run of the program as it would look in cloud9:
This is what I have so far:
#include <iostream>
#include <cstdlib> // Enables use of rand()
#include <ctime>
using namespace std;
int main() {
int num = 0;
int i;
int head=0,tail=0;
srand(4444);
cout << "Enter the number of times you want to toss the coin: "<< endl;
cin >> num;
for (i = 1; i<=num;i++){
if (rand() % 2 == 1){
head++;
}
else{
tail++;
}
}
cout <<"Heads came up "<< (head*20)/float(num) << "% of the time. ";
return 0;
}
Explanation / Answer
#include <iostream>
#include <cstdlib> // Enables use of rand()
#include <ctime>
using namespace std;
double percentHeads(int times)
{
srand(4444);
int i,head = 0;
for (i = 1; i<=times;i++)
if (rand() % 2 == 0) //heads are represented as 0
head++;
return (head*100.0)/times;
}
int main() {
int num;
double result;
cout << "Enter the number of times you want to toss the coin: "<< endl;
cin >> num;
result = percentHeads(num);
cout <<"Heads came up "<< result << "% of the time. ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.