gpt4 book ai didi

c - 二维数组 - 我想找到每行中哪些列中有 1

转载 作者:太空宇宙 更新时间:2023-11-04 04:14:49 25 4
gpt4 key购买 nike

我的输入是这样的:

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 %d\n", 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,但是当行中只有 0 或者有多个 时,这一切都失败了>1。我也想存储这些值。

最佳答案

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

要回答你问题的第二部分,如果你想存储“总和”。只需将 loc[] 设为二维数组,就像 meteor 一样,但有 2 列(行和总和)。即 int loc[row][2].. 当然要确保初始化两列 :)

关于c - 二维数组 - 我想找到每行中哪些列中有 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53270249/

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