如何像Zig-zag算法一样求和

时间:2016-05-31 13:50:38

标签: java math

假设我有2个这样的数据:

x = 1, and {10,20,30}.

我想这样总结:

1 + 10 = 11, 11 + 20 = 31, and 31 + 30 = 61

我的代码。

int x = 1;
int[] arr = {10, 20, 30};
int sum = 0;
for (int i = 0; i < arr.length; i++) 
{
    sum = arr[i] + x;
}

我明白了:

1 + 10 = 11, 1 + 20 = 21, and 1 + 30 = 31 and so on

如何解决这个问题?

3 个答案:

答案 0 :(得分:4)

sum初始化为x,并将arr[i]的值添加到sum,而不要将sum设置为arr[i] + x

int sum = x; // You only want to add x once, so just say the sum is equal to x
for (int i = 0; i < arr.length; i++) 
{
    // You didn´t sum the values up, you just said the sum is equal to your 
    // x value plus the element at arr[i]
    sum += arr[i];
}

答案 1 :(得分:3)

你可以这样做

int[] arr = {10, 20, 30};
int x = 1;
int sum = x;
for (int i = 0; i < arr.length; i++) 
{
    sum = sum + arr[i];
}

您只需要为之前获得的总和添加新值。 所以它就像sum = sum+next_item

答案 2 :(得分:0)

也尝试使用FOR EACH

int sum = 0;
for (int no:arr){
    sum += no;
}