在C中列出并洗牌一副牌

时间:2016-04-13 15:00:51

标签: c

我的项目是使用结构,枚举和字符串开发一个程序,首先按照套装列出一副牌,并按13行和4列排列,然后将它们随机播放并以相同的方式输出随机牌组。这就是我到目前为止所做的:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

typedef struct
{
    char suit;
    char rank[10];

}CARDS;

int main(void)
{
  char str[] = {"Clubs Hearts Diamonds Spades"};
  CARDS deck[52];

  int i;
  int count = 0;
  int num = 1;

  for(i=0; i<52; i++)
  {
   deck[i].suit=str[count];

    //Assigning the card number with switch statement
    switch(num)
    {
        case 1: strcpy(deck[i].rank, "ACE");
            break;
        case 2: strcpy(deck[i].rank, "Deuce");
            break;
        case 3: strcpy(deck[i].rank, "3");
            break;
        case 4: strcpy(deck[i].rank, "4");
            break;
        case 5: strcpy(deck[i].rank, "5");
            break;
        case 6: strcpy(deck[i].rank, "6");
            break;
        case 7: strcpy(deck[i].rank, "7");
            break;
        case 8: strcpy(deck[i].rank, "8");
            break;
        case 9: strcpy(deck[i].rank, "9");
            break;
        case 10: strcpy(deck[i].rank, "10");
            break;
        case 11: strcpy(deck[i].rank, "Jack");
            break;
        case 12: strcpy(deck[i].rank, "Queen");
            break;
        case 13: strcpy(deck[i].rank, "King");
            break;
    }//end switch

    num++;

    //If statement for assigning numbers
    if((i+1)%13==0)
    {
        count++;
        num = 1;
    }//end if

}//end for

//Local Statements
printf("Before Shuffling:\n\n");

for(i=0; i<=52; i++)
{
    printf("%s %c", deck[i].rank, deck[i].suit);
   printf(" ");
    if(count < 3)
        count++;
    else
    {
        printf("\n");
        count = 0;
    }//end else
}//end for
return 0;
}

到目前为止,我没有成功获得正确的订单,我的西装也不会打印出整个单词。这只是我尝试按顺序列出卡片的开始。我也知道我没有使用过任何枚举。不知道该怎么做。请帮忙!

1 个答案:

答案 0 :(得分:2)

  • 您只在结构中存储了一个字符,因此很自然不会打印整套西装字样。
  • 你应该使用const char*数组来填充套装和等级的名称。
  • 避免出现一个错误:第二个i<=52循环中的循环条件for错误。
  • 您应该在进入第二个循环之前初始化count

更正后的代码:

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

typedef struct
{
    char suit[10];
    char rank[10];

}CARDS;

int main(void)
{
  const char* suit_names[] = {"Clubs", "Hearts", "Diamonds", "Spades"};
  const char* rank_names[] = {"ACE", "Deuce", "3", "4", "5", "6", "7", "8", "9", "10",
      "Jack", "Queen", "King"};
  CARDS deck[52];

  int i;
  int count = 0;
  int num = 1;

  for(i=0; i<52; i++)
  {
    strcpy(deck[i].suit, suit_names[count]);

    //Assigning the card number
    strcpy(deck[i].rank, rank_names[num - 1]);

    num++;

    //If statement for assigning numbers
    if((i+1)%13==0)
    {
      count++;
      num = 1;
    }//end if

  }//end for

  printf("Before Shuffling:\n\n");

  count = 0;
  for(i=0; i<52; i++)
  {
    printf("%s %s ", deck[i].rank, deck[i].suit);
    if(count < 3)
      count++;
    else
    {
      printf("\n");
      count = 0;
    }//end else
  }//end for
  return 0;
}

然后,以某种方式引入枚举并实现随机播放。