【发布时间】: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 < cols + i * cols也可以简化为j < cols。if (arr[j] == target)总是只检查第一行。应该是if (arr[i * cols + j] == target)。
标签: c loops for-loop multidimensional-array