gpt4 book ai didi

C++ 跟踪最长的连胜

转载 作者:搜寻专家 更新时间:2023-10-31 01:16:34 24 4
gpt4 key购买 nike

在我的计算机编程课上,我决定编写一个程序来生成随机抛硬币并记录正面和反面的最长连续连续条纹。我搜索了互联网,但没有找到答案。计数显示不正确。即使只是一个提示也会很棒!谢谢,贾斯汀

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;
}

最佳答案

您的代码没有考虑最后 连胜,因为您只在下一个时检查highest_headhighest_tail 翻转是不同的。最后一次翻转,没有下一次翻转。

由于这是家庭作业,我不会建议如何修复您的代码。

关于C++ 跟踪最长的连胜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9013701/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com