For my computer programming class, I decided to make a program that generates a random coin flip and keeps track of the longest consecutive streak for both heads and tails. I have searched the internet and found no answer. The count is not displaying right. Even just a hint would be great!
Thanks,
Justin
int main(){
int number_of_flips;
int coin_flip;
int previous_flip = 2;
int head_count = 0;
int tail_count = 0;
int highest_head = 0;
int highest_tail = 0;
srand(time(NULL));
cout << "Enter the number of coin flips:" << endl;
cin >> number_of_flips;
system("cls");
for(int i = 0; i < number_of_flips; i++){
coin_flip = rand() % 2;
if(coin_flip == 0){
cout << "Heads" << endl;
if(coin_flip == previous_flip){
head_count = head_count + 1;
}
else{
if(head_count > highest_head){
highest_head = head_count;
}
head_count = 0;
}
}
if(coin_flip == 1){
cout << "Tails" << endl;
if(coin_flip == previous_flip){
tail_count = tail_count + 1;
}
else{
if(tail_count > highest_tail){
highest_tail = tail_count;
}
tail_count = 0;
}
}
previous_flip = coin_flip;
}
cout << "The longest run of heads is " << highest_head << endl;
cout << "The longest run of tails is " << highest_tail << endl;
system("pause");
return 0;
}
Here is an example of the output:
Tails
Tails
Tails
Heads
Heads
Tails
Tails
Tails
Tails
Heads
The longest run of heads is 1
The longest run of tails is 2
As a reference, here is my final code that I believe works now:
int main(){
int number_of_flips;
int coin_flip;
int previous_flip = 2;
int head_count = 0;
int tail_count = 0;
int highest_head = 0;
int highest_tail = 0;
srand(time(NULL));
cout << "Enter the number of coin flips:" << endl;
cin >> number_of_flips;
system("cls");
for(int i = 0; i < number_of_flips; i++){
coin_flip = rand() % 2;
if(coin_flip == 0){
cout << "Heads" << endl;
if(coin_flip == previous_flip){
head_count = head_count + 1;
}
else{
if(head_count > highest_head){
highest_head = head_count;
}
head_count = 1;
}
}
if(coin_flip == 1){
cout << "Tails" << endl;
if(coin_flip == previous_flip){
tail_count = tail_count + 1;
}
else{
if(tail_count > highest_tail){
highest_tail = tail_count;
}
tail_count = 1;
}
}
previous_flip = coin_flip;
}
if(head_count > highest_head){
highest_head = head_count;
}
if(tail_count > highest_tail){
highest_tail = tail_count;
}
cout << "The longest run of heads is " << highest_head << endl;
cout << "The longest run of tails is " << highest_tail << endl;
system("pause");
return 0;
}
Your code doesn’t take into account the last streak, because you only check against
highest_headorhighest_tailwhen the next flip is different. On the last flip, there is no next flip.Since this is homework, I’ll refrain from suggesting how to fix your code.