c-2D数组-我想找出每行中哪些列有1

  • 本文关键字:数组 c-2D c arrays
  • 更新时间 :
  • 英文 :


我的输入如下:

15 5
0 0 1 0 0
0 0 1 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0
0 1 0 1 0
0 0 1 0 0
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 1 0 0 0
1 0 0 0 1
0 0 1 0 0
0 0 0 1 0

第一行包含我的数组的行数和列数。基本上,我想找出这些1在数组中的位置。

因此,在前3行中,我想得到3,在第7行中得到1,在第8行中,我们想得到2 3等等

到目前为止,我的代码看起来像这样

#include <stdio.h>
int main() {
int row, column;
FILE* input;
FILE* output;
input = fopen("input.txt", "r");
if (input == 0) {
printf("ERROR couldn't open input.txt");
return 1;
}
if (! fscanf(input, "%d %d", &row, &column)) {
printf("ERROR not recognised value");
fclose(input);
return 2;
} 
output = fopen("output.txt", "w");
int meteor[row][column];
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
fscanf(input, "%d", &meteor[i][j]);
}
}
int sum;
int loc[row];
for (int i = 0; i < row; i++) {
sum = 0;
for (int j = 0; j < column; j++) {
sum += meteor[i][j];
if (meteor[i][j] == 1) {
loc[i] = (j + 1);
}
}
printf("%d %dn", loc[i], sum);
}
fclose(input);
fclose(output);
return 0;
}

我的输出是:

3 1
3 1
3 1
0 0
-1 0
1 1
4 2
3 1
5 1
0 0
4214921 0
2 1
5 2
3 1
4 1

第一列显示了一些位置,第二列显示了行中有多少个1,但当行中只有0s或有多个1时,这一切都会失败。我也想存储这些值。

您需要初始化loc[]。。如果您仔细查看您的代码,您只能在if (meteor[i][j] == 1)的条件下填充它。。。但是你为i的每个索引打印它,这将打印未初始化的内存(即未知(。

为了回答问题的第二部分,如果你想存储"总和"。只需将loc[]制作成一个类似于meteor的2d数组,但包含2列(行和和(。即int loc[row][2]。。当然,要确保初始化两列:(

最新更新