我被這個程序卡住了,似乎無法弄清楚它爲什麼會崩潰。它符合要求,但在運行時收集用戶輸入時會停止響應,迫使用戶關閉。C++繪製卡片故障排除
它所要做的就是詢問用戶他們想繪製多少張牌。一旦進入該程序,應該隨機選擇該手的數量,然後關閉。提前致謝!!
代碼:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
using namespace std;
struct Card //defines a custom "structured" variable type
{
int kind;
char kindDisplay;
string suit;
};
bool havePair (Card hand[])
{
int count[13];
int i,k;
bool pair;
for (i=0; i <=12; i++)
count[i] = 0;
for (i=1; i<= 5; i++)
count[hand[i].kind]++;
pair = false;
for (i=0; i <= 12;i++)
if (count[i] > 1)
pair = true;
return pair;
}
int main()
{
int numHands;
int pairCount =0;
bool hasBeenDrawn[52]; // has given card been drawn already?
int suitDrawn; // 0=clubs,1=diamonds,2=spades,3=hearts
int kindDrawn; // index of kind from 0 to 12,
// representing 2,3,...9,10,J,Q,K,A
Card hand[6];
int num; // randomly generated card to pick (from 0 to 51).
int cardCount; // counts how many cards have been drawn;
int i,j;
unsigned int seed; // seed for random number generator
seed = time(0);
srand(seed);
cout << "Enter # of hands to draw: ";
cin >> numHands;
cout << endl;
for (j=1; j<= numHands; j++)
{
for (i=0; i < 52; i ++)
hasBeenDrawn[i] = false;
for (cardCount=1; cardCount <=5; cardCount++) // draw 5 cards
{
do
{
num = rand()%52; // get random number between 0 & 51 inclusive
} while (hasBeenDrawn[num] == true);
hasBeenDrawn[num] = true;
suitDrawn = num/13; // quotient will be 0, 1, 2, or 3
switch (suitDrawn)
{
case 0: hand[cardCount].suit = " clubs ";
break;
case 1: hand[cardCount].suit = " diamonds";
break;
case 2: hand[cardCount].suit = " spades ";
break;
case 3: hand[cardCount].suit = " hearts ";
break;
}
kindDrawn = num % 13;
hand[cardCount].kind = kindDrawn;
if (kindDrawn == 12) hand[cardCount].kindDisplay = 'A';
else if (kindDrawn == 11) hand[cardCount].kindDisplay = 'K';
else if (kindDrawn == 10) hand[cardCount].kindDisplay = 'Q';
else if (kindDrawn == 9) hand[cardCount].kindDisplay = 'J';
else if (kindDrawn == 8) hand[cardCount].kindDisplay = 'T'; // a "ten"
else
hand[cardCount].kindDisplay = (char)(kindDrawn + 50);
if (havePair(hand) == true)
pairCount++;
}
//Note: ASCII character codes for '0','1',...,'9' are 48 through 57
} // end for loop (cardCount = 1 to 5) draw 5 cards
cout << endl << endl;
cout << fixed << setprecision(2);
cout << "Experimental % of pairs: " << (double)numHands*100.0 << endl;
cout << "Theoretical % of pairs: " << (2598960-1317888)/(double)(2598960)*100.0 << endl; //approximate # of hands that don't have a pair
cout << endl;
return 0;
}
運行在一個調試器或添加一些打印,找出到底是怎麼回事 - 如果它「凍結」,聽起來像是陷入循環... ps數組從0開始,而不是1. – John3136
@ John3136感謝您的回覆!我在哪裏可以得到一個C++調試器?我從來沒有用過這種語言。我試圖找到一個,但找不到任何東西。 – TheWiz
什麼操作系統? gdb是第一個想到的問題。如果你沒有添加調試器,打印會顯示你的代碼到達哪些位以及哪些位不是; t。 – John3136