C++ help! In addition to the current program, ** Write a function named percentH
ID: 3668627 • Letter: C
Question
C++ help!
In addition to the current program,
** 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)
Here is an example run of the program as it would look in cloud9:
#include <iostream>
using namespace std;
int add(int a, int b){
return a+b;
}
int subtract(int a, int b){
return a-b;
}
int main() {
int num1 = 0;
int num2 = 0;
int sum = 0; //sum of numbers
int diff = 0; //difference of numbers
cout << "Enter the first integer: ";
cin >> num1;
cout << "Enter the second integer: " << endl << endl;
cin >> num2;
cout << "First Integer: " << num1 << endl;
cout << "Second Integer: " << num2 << endl << endl;
// Call add function
sum = add(num1, num2);
// FIXME (4) Call subtract function
diff = subtract(num1, num2);
// FIXME (6) Output result of num1 + num2
cout << num1 << " + " << num2 << " = " << sum << endl;
// FIXME (8) Output result of num1 - num2
cout << num1 << " - " << num2 << " = " << diff << endl;
return 0;
}
Explanation / Answer
#include <iostream>
#include <stdlib.h>
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:";
cin >> num;
for (i = 1; i<=num;i++){
if (rand() % 2 == 1){
head++;
}
else{
tail++;
}
}
cout <<"Heads came up "<< (head*100)/float(num) << "% of the time. ";
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.