【问题标题】:Storing user input into 2D array and break out?将用户输入存储到二维数组中并突破?
【发布时间】:2014-04-06 23:08:07
【问题描述】:

我正在做我的课堂作业,但我被困在二维数组、嵌套循环和特定条件下。

void main (){
int a;
int b;
int orders[100][4];
char confirm[50];


//printf("Enter the number of boxes of whistles you need on this invoice");
for (a = 0; a <=100; a++){
    for(b =0; b <4; b++){
    printf("Enter the number of boxes of whistles you need on this invoice");
    scanf("%d", &orders[a][b]);
    while (orders[a][b] <0)
    {
    printf("Invalid value! Please check the number.");
    scanf("%d", &orders[a][b]);
    }
    printf("Enter the number of boxes of bells you need on this invoice.");
    scanf("%d", &orders[a][b]);
    while (orders[a][b] <0)
    {
    printf("Invalid value! Please check the number.");
    scanf("%d", &orders[a][b]);
    }
    printf("Enter the number of boxes of horns you need on this invoice");
    scanf("%d", &orders[a][b]);
    while (orders[a][b]<0)
    {
    printf("Invalid value! Please check the number.");
    scanf("%d", &orders[a][b]);
    }

    printf("Do you want to enter more orders?");
    scanf("%s", confirm);
    if (strcmp(confirm, "N") == 1){
        break;
    }
}

如您所见,我应该用用户输入填充二维数组(如果您愿意的话,可以使用发票图表)。我不确定我的代码是否正确。最后,当用户说 N 表示“否”而程序询问“你想输入更多订单吗?”时,我试图跳出循环。当我尝试代码时,它会询问所有问题,并且似乎存储了它,但即使我把 N 放在最后,我也无法跳出循环。

所以...我的问题是

  1. 我存储的带有用户输入的二维数组的编码是否正确?
  2. 当我说 N(或任何其他字母或数字)时,如何退出循环(或结束循环)?

谢谢!

【问题讨论】:

    标签: arrays store nested-loops break


    【解决方案1】:

    我知道为别人做作业很伤心,但不管怎样,我们开始吧。

    数组可以是动态的,没有固定大小 [100][4]

    清空你的数组,否则它会被大量数据填满,你将无法得到任何明智的选择。

    b 仅在完成循环后增加。您甚至不需要循环,此时您的所有数据都被写入完全相同的位置 [a][b]。考虑跳过该循环并编写 [a][0]、[a][1] 等。

    strcmp(confirm, "N") 为真时返回 0。

    就目前而言,您处于双循环中。为了解决这个问题,您很可能希望将循环放在一个单独的函数中,然后调用return 而不是break。从技术上讲,您现在也可以这样做,但是您将终止主函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-20
      • 2018-03-22
      • 1970-01-01
      • 2021-12-07
      • 2020-05-23
      相关资源
      最近更新 更多