【问题标题】:Sum of arrays in CC中的数组总和
【发布时间】:2024-01-14 15:54:01
【问题描述】:

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

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}};

【问题讨论】:

  • int sumofcolumn0 = productionSP[0][0] + productionSP[1][0] + productionSP[2][0]; 用循环变量替换最后一个 0s 并进行其他适当的更改:)
  • @pmg 非常感谢,比我想象的要容易。

标签: c arrays math sum dev-c++


【解决方案1】:

你可以使用如下循环来做到这一点 -

#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 列。当矩阵大小不同时,您可以相应地更改循环条件。

希望这会有所帮助!

【讨论】:

  • 非常感谢您对问题的补充,已经让您开阔了思路