数组中的元素的总和 [英] Sum of elements in an array

查看:128
本文介绍了数组中的元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个简单的赋值一个夏天的Java课程,只是希望你们能来看看我的code,看看我做的方式是最好的方式。其目的是创建一个简单的 INT 阵列,至少有25个元素,并使用循环遍历它,并添加了所有的元素。我有一些问题,但看起来像我得到它的工作。我工作了之后,我做了一些研究,看到那里的人用For Each循环(循环增强)一些类似的东西。那会是一个更好的选择吗?我有点困惑在使用该反对常规循环的最佳方式。

不管怎样,帮助我任何意见或批评是一个更好的程序员!

 公共类遍历{    公共静态无效的主要(字串[] args){        INT absenceTotal = 0;
        //使用缺勤30天初始化数组。
        INT absencesArr [] = {1,3,0,9,8,23,1,
                11,23,5,6,7,10,1,5,
                14,2,4,0,0,1,3,2,1,
                1,0,0,1,3,7,2};        的for(int i = 0; I< absencesArr.length;我++){
            absencesArr [I] + = absenceTotal;
            absenceTotal = absencesArr [I]
        }
        的System.out.println(有+ absenceTotal +缺失的那一天。);
    }
}


解决方案

不要修改该数组。我想preFER的 的for-each 循环。你应该认为有可能是一个非常大的数字的学生,所以我可能会使用 。和格式化输出。一起投入像

 长总和= 0;
对于(INT I:absencesArr){
    总和+ =我;
}
//的System.out.println(有+总和+缺失的那一天。);
System.out.printf(有%d个没啥当日%N,总和);

I'm working on a simple assignment for a summer java course and was just hoping you guys could take a look at my code and see if the way I did it is the best way. The purpose is to create a simple int array with at least 25 elements and use a loop to traverse it and add up all the elements. I had some issues but looks like I got it to work. After I work it out I did a little research and saw some similar stuff where people were using a For Each loop (enhanced loop). Would that be a better option? I'm kinda confused on the best ways to use that opposed to a regular for loop.

Anyway, any comments or criticism in helping me be a better programmer!

public class Traversals {

    public static void main(String[] args) {

        int absenceTotal = 0;
        // initialize array with 30 days of absences.
        int absencesArr[] = { 1, 3, 0, 9, 8, 23, 1, 
                11, 23, 5, 6, 7, 10, 1, 5,
                14, 2, 4, 0, 0, 1, 3, 2, 1, 
                1, 0, 0, 1, 3, 7, 2 };

        for (int i = 0; i < absencesArr.length; i++) {
            absencesArr[i] += absenceTotal;
            absenceTotal = absencesArr[i];
        }
        System.out.println("There were " + absenceTotal + " absences that day.");
    }
}

解决方案

Don't modify the array. I would prefer the for-each loop. And you should consider that there may be a very large number of students, so I would probably use a long for sum. And formatted output. Putting that together into something like

long sum = 0;
for(int i : absencesArr) {       
    sum += i;
}   
// System.out.println("There were " + sum + " absences that day.");   
System.out.printf("There were %d absences that day.%n", sum);

这篇关于数组中的元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆