简体   繁体   English

如何计算 java 中的 3D 数组中的总和?

[英]How to calculate sum in a 3D Array in java?

I want to calculate the total of each row of a multidimensional array I tried playing around with the loops I have initialized all the variables however im not sure how I should go about calculating the sum.;我想计算一个多维数组的每一行的总数,我尝试使用循环来初始化所有变量,但是我不确定我应该如何 go 来计算总和。

//declaring array
    double calls [][][] = 
        {
                {{500,600,800},{700,800,900},{899,929,828},{292,900,727},{234,424,586},{997,734,876},{235,543,948}},
                {{112,223,893},{234,848,455},{454,929,435},{727,827,636},{334,828,929},{382,938,929},{233,456,346}},
                {{221,434,911},{374,647,338},{364,921,726},{919,823,221},{112,334,737},{912,261,562},{535,654,821}},
                {{233,838,912},{263,523,393},{737,373,928},{828,736,636},{325,324,876},{434,858,495},{239,458,959}}
        for(int weeks=0;weeks<4;weeks++) {
                    for(int callNum=0;callNum<7;callNum++) {
                        for(int dept=0;dept<3;dept++) {
                        counter+=(calls[weeks][callNum][dept]);
                        counter++;
                    }
                }
            }
            for(int week=0;week<calls.length;week++) {
                for(int days=0;days<calls[week].length;days++) {
                    for(int resp=0;resp<calls[week][days].length;resp++) {
                        total=+counter;
                        counter++;

            }

                }
                System.out.println("Week "+(week+1)+ "= "+ total);
                total=0.0;
            }

If you want to calculate the sum of all elements in a week, you could simply change your second loop to:如果要计算一周内所有元素的总和,只需将第二个循环更改为:

for (int week = 0; week < calls.length; week++) {
        for (int days = 0; days < calls[week].length; days++) {
            for (int resp = 0; resp < calls[week][days].length; resp++) {
                total += (calls[week][days][resp]);
            }

        }
        System.out.println("Week " + (week + 1) + "= " + total);
        total = 0.0;
    }

which will print you total of each week.这将打印您每周的总数。 Here is an output:这是一个 output:

Week 1= 14452.0
Week 2= 12148.0
Week 3= 11827.0
Week 4= 12368.0

Hope it helps!希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM