数组列表的总和

我正在尝试对 arrayList 的列进行平均(moy),但我需要先对其进行求和,我不知道该怎么做


    int sumX = 0;

    val = new ArrayList<>();

    float moy[] = new float[3];


          if (i < 100) {

                    val.add(sensorEvent.values);

                i++;

            } else {

                for (; i > 0; i--);

                {

                    sumX = ?

                    moy[0] = sumX/100;

                }

                val.clear();

                i = 0;

}


尚方宝剑之说
浏览 128回答 4
4回答

天涯尽头无女友

使用DoubleStream:变种:输入是一个数组doubledouble[] values = new double[] {1.1D, 2.33D, 4D}; double average = DoubleStream.of(values).average().getAsDouble();输入是ArrayList一个IntegerArrayList<Integer> values = new ArrayList<>(); values.add(1); values.add(42); values.add(-1); double average = values.stream().mapToDouble(value -> (double) value).average().getAsDouble();

哈士奇WWW

您可以使用以下代码片段:(用 kotlin 编写)fun main() {val s: List<Float> = listOf(1.2F, 1.4F, 5.6F)&nbsp;// populate it with your custom list datavar sum = 0Fs.forEach { it ->&nbsp; &nbsp; sum+=it}println("Sum = $sum and avg = ${sum/(s.size)}")}这是java解决方案:class Ideone{&nbsp;public static void main (String[] args) throws java.lang.Exception&nbsp;{&nbsp; &nbsp; List<Float> s = new ArrayList(Arrays.asList(1.2F, 1.3F, 5.4F, 6.5F));&nbsp; &nbsp; Float sum = 0F;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for (int i=0; i< s.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; sum+=s.get(i);&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;System.out.println("Sum: "+sum+" and Avg: "+sum/(s.size()));}&nbsp; &nbsp;}

慕的地6264312

以下是如何对 ArrayList 中的所有值求和ArrayList<Integer> nums = new ArrayList<>();// Populate ArrayListint sum = 0;for (int num : nums) {&nbsp; &nbsp; sum += num;}// Do whatever you want with sum after

翻阅古今

只需在流中使用平均收集器,您不必计算元素的SUM和NUMBER:ArrayList<Double> numbers = new ArrayList<>() {{&nbsp; add(1d);&nbsp; add(2.45d);&nbsp; add(100d);}};final double average = numbers.stream()&nbsp; .collect(Collectors.averagingDouble(d -> d));moy[0] = average;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java