数组的累积和

5 java arrays loops for-loop

因此,我正在研究一个以获取数组的累加总和为重点的问题,例如,如果我有一个({0,2,3,-1,-1})数组,它将返回{0,2,5 ,4,3} ...,或者如果您有[1、2、3、4、5、6、7、8、9、10]数组,则应返回[1、3、6、10、15, 21,28,36,45,55] ...

现在,我正面临两个问题,一个是我必须使用给定的方法,而我正在为返回的内容而苦苦挣扎,因为total不会。。对于我的代码,我知道它可以将数组的总和相加,但不能如我的示例中所示的累计金额。任何准则都将有所帮助。

public int[] makeCumul(int[] in) {
    int[] out = { in.length };
    int total = 0;
    for (int i = 0; i < out.length; i++) {
        total += out[i];
    }
    return total;
}
Run Code Online (Sandbox Code Playgroud)

Jaa*_*ole 5

部分不读取 in 数组,但也不更新 out 数组,也不返回它。这应该对你有用。

public int[] makeCumul(int[] in) {
    int[] out = new int[in.length];
    int total = 0;
    for (int i = 0; i < in.length; i++) {
        total += in[i];
        out[i] = total;
    }
    return out;
}
Run Code Online (Sandbox Code Playgroud)