對於我的計算機編程課程,我決定製作一個程序,生成一個隨機硬幣翻轉並記錄頭部和尾部最長的連續條紋。我搜查了互聯網,發現沒有答案。計數顯示不正確。即使只是一個提示將是偉大的! 謝謝, 賈斯汀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
該程序不計算連勝權。 –