首页 > 解决方案 > 检查二维数组中的无效值

问题描述

有没有办法为第一列设置 1-13 限制,为第二列设置 1-4 限制

我的输出如下所示:

您选择的卡值和花色是:

1 2

3 4

5 6

7 8

9 10

到目前为止,这是我的代码,我知道 while 循环会影响我的二维数组中的所有值。我不知道如何设置两个不同的限制至于我现在的输入,它只接受 1 - 13 之间的值

void getCard(int card[][2])

{

int i, j;
printf("\nPlease enter the card value followed by its suit\n");
for (i = 0; i < 5; i++)
{
    for (j = 0; j < 2; j++)
    {
        scanf("%i", &card[i][j]);

        while (card[i][j] > 13|| card[i][j] < 1)
        {
            printf("\nOnly enter card value between 1 to 13.\n");
            scanf("%i", &card[i][j]);
        }
    }
 }

 }

void main(void)
{
int i, j;
int card[5][2];

getCard(card);

printf("\nThe card value and suit that you've chosen are:\n");
for (i = 0; i < 5; i++)
{
    for (j = 0; j < 2; j++) 
    {
        printf("%i  ", card[i][j]);
        if (j == 1)
        {
            printf("\n");
        }
    }
}
}

标签: c++visual-c++

解决方案


您可以执行以下操作:

for (j = 0; j < 2; j++)//loop by columns
{
    int rest=13;//for the first column
    if (j==1)
        rest=4;//for the second column
    for (i = 0; i < 5; i++)
    {
    scanf("%i", &card[i][j]);
        while (card[i][j] > rest|| card[i][j] < 1)//the loop depends on the value of rest
        {
            printf("\nOnly enter card value between 1 to %i.\n",rest);
            scanf("%i", &card[i][j]);
        }
    }
}

如果您仍然需要遍历行:

for (i = 0; i < 5; i++)//loop by rows
{
    for (j = 0; j < 2; j++)        
    {
    int rest=13;//for the first column
    if (j==1)
        rest=4;//for the second column
    scanf("%i", &card[i][j]);
        while (card[i][j] > rest|| card[i][j] < 1)//the loop depends on the value of rest
        {
            printf("\nOnly enter card value between 1 to %i.\n",rest);
            scanf("%i", &card[i][j]);
        }
    }
}

推荐阅读