gpt4 book ai didi

C - 嵌套循环和堆栈?

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:53 28 4
gpt4 key购买 nike

我试图在一维数组中找到目标的位置,该数组就像一个包含行和列的表格。我可以使用 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。

最佳答案

问题不在于赋值,而在于错误的循环和 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
}
}
}

关于C - 嵌套循环和堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49469437/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com