【发布时间】:2010-05-10 21:06:53
【问题描述】:
您好,我正在开发一个程序,我必须初始化一副纸牌。我正在使用一个结构来表示一张卡片。但是我没有正确填写它,因为当我显示一副牌时我得到一堆零。我相信我的错误在这一行,但我不确定:
struct card temp = {"Clubs", value, false};
代码:
void initCards(){
int count = 0;
int location = 0;
const int hand = 12;
//add hearts
int value=2;
while( count < hand ){
struct card temp = {"Hearts", value, false};
cards[location] = temp;
value++;
count++;
}
count = 0;
//add diamonts
value = 2;
while( count < hand ){
struct card temp = {"Diamonds", value, false};
cards[count] = temp;
value++;
count++;
}
//add spades
count = 0;
value = 2;
while( count < hand ){
struct card temp = {"Spades", value, false};
cards[count] = temp;
value++;
count++;
}
//add clubs
count = 0;
value = 2;
while( count < hand ){
struct card temp = {"Clubs", value, false};
cards[count] = temp;
value++;
count++;
}
//print the deck
for(int i=0; i<52; i++){
cout << cards[i].type << " " << cards[i].rank << endl;
}
}
我不敢相信我正在使用 count 作为我的迭代器... location 是我打算使用的。而且由于我从 2 开始数,手应该是 13。有时你只需要休息一下,然后回来看看错误。这工作正常:
void initCards(){
int count = 0;
int location = 0;
const int hand = 13;
//add hearts
int value=2;
while( count < hand ){
struct card temp = {"Hearts", value, false};
cards[location] = temp;
value++;
location++;
count++;
}
count = 0;
//add diamonts
value = 2;
while( count < hand ){
struct card temp = {"Diamonds", value, false};
cards[location] = temp;
value++;
location++;
count++;
}
//add spades
count = 0;
value = 2;
while( count < hand ){
struct card temp = {"Spades", value, false};
cards[location] = temp;
value++;
location++;
count++;
}
//add clubs
count = 0;
value = 2;
while( count < hand ){
struct card temp = {"Clubs", value, false};
cards[location] = temp;
value++;
location++;
count++;
}
for(int i=0; i<52; i++){
cout << cards[i].type << " " << cards[i].rank << endl;
}
}
【问题讨论】:
-
代码审查:尝试查看您的代码,看看您是否可以减少重复自己。将来还要使用
for循环,它们更容易发现错误。在编写代码之后,您会停止经常使用while。尝试首先通过每个套件的外部for循环。
标签: c++ arrays struct structure new-operator