1

所以伙计们,下面是我的代码的一部分,我需要对每一列中的内容求和,并对整个表格中的内容求和,你能帮我解决一下如何使用代码中的数组吗?只是说话对我没有帮助,我想在代码中看到它以更好地理解它。

void main(void){
//Matrix Declaration and Initialization with the Production Data of each Branch; 
//Format: productionXX[shift][week];
    int productionSP[3][4] = {{1000, 1030,  900,  990},
                              {1010, 1045, 1100, 1015},
                              {1050, 1065, 1075, 1100}};
4

1 回答 1

2

您可以使用以下循环来执行此操作 -

#include <stdio.h>

int main() {
    int productionSP[3][4] = {{1000, 1030,  900,  990},
                              {1010, 1045, 1100, 1015},
                              {1050, 1065, 1075, 1100}};
    int column_sum[4]={0};
    int final_sum=0;

    // i denotes iterating over each of the rows
    for(int i=0;i<3;i++){
        // j denotes iterating over each column of each row
        for(int j=0;j<4;j++){
            final_sum+=productionSP[i][j];
            column_sum[j] +=  productionSP[i][j];
        }
    }
    printf("column sums - \n");
    for(int i=0;i<4;i++){
        printf("Column #%d - %d\n",i+1,column_sum[i]);
    }
    printf("final_sum = %d",final_sum);
}

输出 :

column sums -                                                                                                                                                                               
Column #1 - 3060                                                                                                                                                                            
Column #2 - 3140                                                                                                                                                                            
Column #3 - 3075                                                                                                                                                                            
Column #4 - 3105                                                                                                                                                                            
final_sum = 12380

您可以根据productionSP数组更改循环中断条件。现在它有静态的 3 行和 4 列。当矩阵大小不同时,您可以相应地更改循环条件。

希望这可以帮助 !

于 2020-06-28T20:02:14.937 回答