【问题标题】:C - Nested loops and stack?C - 嵌套循环和堆栈?
【发布时间】:2018-09-03 07:08:57
【问题描述】:

我正在尝试在一维数组中查找目标的位置,该数组的作用类似于具有行和列的表。我可以使用divide和mod来做到这一点,但我坚持使用嵌套循环来找到它。具体来说,我似乎无法在嵌套循环中分配值。 这是我的代码:

#include <stdio.h>

int main()
{
   int arr[9] =  // act as a 3 X 3 table
   { 2, 34, 6,
     7, 45, 45,
     35,65, 2
   };
   int target = 7;// r = 1; c = 0
   int r = 0; // row of the target
   int c = 0; // col of the target
   int rows = 3;
   int cols = 3;
   for (int i = 0; i < rows; i++){
       for (int j = 0; j + i * cols < cols + i * cols; i++ ){
           if (arr[j] == target){
           c = j; // columns of the target
           r = i; // rows of the target
           }
       }
   }
   printf ("%d, %d",c, r);
    return 0;
}

代码输出:0,0。

【问题讨论】:

  • 最里面的循环有一个错字:i++ 应该是j++j + i * cols &lt; cols + i * cols 也可以简化为 j &lt; colsif (arr[j] == target) 总是只检查第一行。应该是if (arr[i * cols + j] == target)

标签: c loops for-loop multidimensional-array


【解决方案1】:

问题不在于分配,而在于错误的循环和if 条件。

  • 外层循环应该遍历i
  • 内部循环应该遍历j
  • 在两个循环中,要评估的单元格是i * cols + j

把它们放在一起,你会得到:

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++ ) {
        if (arr[i * cols + j] == target) {
            c = j; // columns of the target
            r = i; // rows of the target
        }
    }
}

【讨论】:

  • 应该把arr[i * rows + j]写成arr[i * cols + j]吗?当cols == rows时,没关系,但如果矩阵不是方阵,那就有关系了。
  • @JonathanLeffler arg,是的。没有注意到错误,因为它们在 OP 中是相同的。已编辑并修复,感谢您的关注!
【解决方案2】:

由于arr 是一维数组并且在for 循环内,对于任何ij 将达到最大值3,因此它不会在arr[3] 之后进行检查

为了避免这个问题,将int pointer指向arr并进行如下操作

int *p = arr;
for (i = 0; i < rows; i++){
        for ( j = 0; j  < cols ; j++ ){
                if (p[j] == target){
                        c = j; // columns of the target
                        r = i; // rows of the target
                }
        }
        p = p + j;/*make p to points to next row */
}

【讨论】:

  • 您确定您的“下标”计算 - *(p + i + j)?最好写成p[i + j](实际上是使用下标符号),但这样还是错了;它需要在算术中考虑列数,不是吗?
  • 感谢@JonathanLeffler 我没有注意到这一点。我修改了答案。
  • 嗯……我明白了。现在你在计算中不用i,你仍然不用cols。你试过你的代码吗? (仅供参考:在我检查代码之前,我通常不会在 SO 上发布答案 - 或者,有时,我会发布答案然后检查它,令人沮丧的是,最终会根据以下情况稍微改变答案检查。)
【解决方案3】:

更好的解决方案是只使用一个循环:

for (int i = 0; i < rows * cols; i++){
    if (arr[i] == target){ 
        r = i / 3;
        c = i % r;
    }
}

【讨论】:

    猜你喜欢
    • 2011-06-11
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多