c++ - 检查二维数组中的无效值
问题描述
有没有办法为第一列设置 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");
}
}
}
}
解决方案
您可以执行以下操作:
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]);
}
}
}
推荐阅读
- python - 数量增加百分比第 2 部分
- reactjs - 在同一端口 80 上运行用于后端服务器代码的 Docker 容器和用于 React 前端代码的 Nginx
- powershell - 我需要在 Powershell 中获取我的 smb 共享的网络路径并将其输出到文本文档
- c# - 打开的 Oracle 连接过多
- python - Python 脚本使用的内存超出了应有的范围
- javascript - 在 javascript 中更改 Textarea 的值
- python - XlsxWriter 未向空单元格添加底部边框
- python-3.x - 如何抓取伪装成 unicode 的 href(例如 \u003ca href=\)
- sql - 这个 SQL 查询和连接是如何在 dplyr 中完成的?
- c - JUMP 表接近 .text 部分的末尾