对于我的计算机编程课程,我决定制作一个程序,生成一个随机硬币翻转并记录头部和尾部最长的连续条纹。我搜查了互联网,发现没有答案。计数显示不正确。即使只是一个提示将是伟大的! 谢谢, 贾斯汀C++保持最长的连续记录
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;
}
下面是输出的一个例子:
Tails
Tails
Tails
Heads
Heads
Tails
Tails
Tails
Tails
Heads
The longest run of heads is 1
The longest run of tails is 2
作为参考,这是我最后的代码,我认为现在的工作:
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;
}
什么问题?你会得到什么错误? –
对我来说很不错 – levis501
该程序不计算连胜权。 –