简体   繁体   English

对数组元素的奇数索引求和

[英]Summing the odd indexes of an array element

I have this program, which does a whole heap of stuff but the part i'm having trouble with is summing the odd indexes in an arraylist. 我有这个程序,它完成了很多工作,但是我遇到的问题是将arraylist中的奇数索引求和。

Every 1, 3, 5, 7, etc. I need to sum and add to a variable. 每1、3、5、7等。我需要求和并添加到变量中。 The variable is of datatype BigFraction and the ArrayList - knowledge takes BigFractions only . 变量的数据类型为BigFractionArrayList-knowledge仅采用BigFractions

So originally I had 所以最初我有

 //Returns the combined probability (the odd indexes of the arraylist)
public BigFraction weight() {
    BigFraction sum;
    if (knowledge.indexOf(knowledge)%2 == 1)
        sum+ = no idea what to put in here
        return sum;
    }
}

I'm really not sure if this is the right syntax for getting indexes of an Arraylist either... I guess you could use a .add or something too, but if anyone could shed light that would be awesome. 我真的不确定这是否是获取Arraylist索引的正确语法……我想您也可以使用.add或其他名称,但是如果有人可以发现它真棒。

Cheers, 干杯,

Sim

Try this out : 试试看:

// Returns the combined probability (the odd indexes of the arraylist)
public BigFraction weight() {
    BigFraction sum;
    for (int index = 1; index < knowledge.size(); index = index + 2) {
        sum = sum.add(knowledge.get(index));
    }

    System.out.println("Sum is  " + sum);

    return sum;
}

Here is a hint: you already know what the odd indices are. 这是一个提示:您已经知道什么是奇数索引。 You've listed them in your question. 您已在问题中列出了它们。 All you have to do is find a way to loop over them. 您要做的就是找到一种遍历它们的方法。

Once you've figured that out, you'll need to find a way to get the element at the given index. 一旦弄清楚了,就需要找到一种方法来获取给定索引的元素。

The rest, I am sure, will be easy. 我敢肯定,其余的将很容易。

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

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