一直在遵循项目教程,并想添加我自己的shuffle方法,输出是正确的,但是一旦我使用我的shuffle方法,我得到两个黑桃的荒谬值,例如(-68218624的黑桃)或(32762的黑桃)其他所有输出都很好。试着找出问题所在。
#include <iostream>
using namespace std;
enum class Suits{
Clubs,
Diamonds,
Hearts,
Spades
};
enum class Names{
Two = 2,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
Ace
};
struct Card{
Names name;
Suits suit;
int value;
void printCard(){
printValue();
cout << " of ";
printSuit();
cout << endl;
}
void printValue(){
cout << value;
}
void printSuit(){
if(suit == Suits::Clubs){
cout << "clubs";
}
else if(suit == Suits::Diamonds){
cout << "diamonds";
}
else if(suit == Suits::Hearts){
cout << "hearts";
}
else{
cout << "spades";
}
}
};
struct Deck{
Card arrCards[52];
void printCards(){
for(int col = (int)Suits::Clubs; col <= (int)Suits::Spades; col++){
for(int row = (int)Names::Two; row <= (int)Names::King; row++){
int index = (13 * col) + row -1;
arrCards[index].printCard();
}
}
}
void SetupCards(){
for(int col = (int)Suits::Clubs; col <= (int)Suits::Spades; col++){
for(int row = (int)Names::Two; row <= (int)Names::King; row++){
Card c;
c.suit = (Suits)col;
c.name = (Names)row;
c.value = (int)c.name;
int index = (13 * col) + row -1;
arrCards[index] = c;
}
}
}
int deckSize(){
return sizeof(arrCards)/sizeof(arrCards[0]);
}
void shuffleDeck(Card deck[], int length){
Card temp;
int randomIndex = 0;
for(int i = 0; i < length; i++){
randomIndex = rand() % (length);
temp = deck[i];
deck[i] = deck[randomIndex];
deck[randomIndex] = temp;
}
}
};
int main(){
Deck deck;
cout << endl;
deck.SetupCards();
deck.printCards();
cout << "The deck has this many cards: " << deck.deckSize() << endl;
deck.shuffleDeck(deck.arrCards, deck.deckSize());
deck.printCards();
cout << endl;
}
//洗牌后输出方法示例:黑桃5梅花5方块7黑桃32762梅花11
for(int row = (int)Names::Two; row <= (int)Names::King; row++){
您只初始化了48张牌。你打了所有四个花色,但你只初始化了第2到k的等级。52卡数组中的最后四个插槽未初始化。