?Write a class named Coin. The Coin class should have the following member varia
ID: 638740 • Letter: #
Question
?Write a class named Coin. The Coin class should have the following member variable: ?
?Write a program that demonstrates the Coin class. The program should create an instance of the class and display the side that is initially facing up. Then, use a loop to toss the coin 20 times. Each time the coin is tossed, display the side that is facing up. The program should keep count of the number of times heads is facing up and the number of times tails is facing up, and display those values after the loop finishes. ?
Explanation / Answer
#include<iostream>
#include<string>
#include<stdlib.h>
#include<time.h>
using namespace std;
class Coin{
private :
string sideUp;
public :
Coin(){
//srand(time(0));
int side = rand()%2;
if(side == 0){
sideUp = "heads";
}else{
sideUp = "tails";
}
}
void toss(){
//srand(time(0));
int side = rand()%2;
if(side == 0){
sideUp = "heads";
}else{
sideUp = "tails";
}
}
string getSideUp(){
return sideUp;
}
};
int main(){
Coin c;
int headCount = 0, tailCount = 0;
cout << "Initial value on top : " << c.getSideUp() << endl;
for(int i=0; i<20; i++){
c.toss();
string side = c.getSideUp();
cout << side << endl;
if(side.compare("heads") == 0){
headCount++;
}else{
tailCount++;
}
}
cout << "Number of times head appears on top is " << headCount << endl;
cout << "Number of times tail appears on top is " << tailCount << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.