如何添加数组的偶数和奇数的和 [英] how to add a sum of even and odd number of an array
问题描述
我想从一个递归数组中获得偶数的和,然后将一个奇数的和加在一起。我试图循环通过数组,以便得到偶数,但它保持返回第一个索引。请帮助和提前感谢。
i am trying to get the sum of even numbers from a recursive array and the sum of an odd number and then add both sums together. i am trying to loop through the arrays so that to get the even numbers but it keep return the first index. please help and thanks in advance..
我的目标是取数组2,1,5,9,8,4取偶数索引,并将其添加到奇数索引。 a [0] = 2,a [1] = 1,a [2] = 5,a [3] = 9,a [4] = 8,所以它需要(2 + 5 + 8) - (1 + 9 + 4)= 1
my aim is to take in array 2,1,5,9,8,4 take the even index and add it to the odd indexes. a[0]=2,a[1]=1,a[2]=5, a[3]=9, a[4]=8, a[5]=4. so it would take (2+5+8)-(1+9+4)=1
这是我到目前为止我不熟悉递归我的代码可能已关闭
this is what i got so far i am not familiar with recursive so my code might be off
int calc(int *a, int size)
{
if(size==1 || size==0)
return a[0];
for(int i=0; i<size; i++){
if(i%2==0){
int sum_i = a[i];
int m=calc(a, size-1);
if(m>a[size-1])
return m;
}
}
for(int j=0; j<size; j++){
if(j%2!=0);
int sum_j = a[j];
return sum_j;
}
int sum = a[i] - a[j];
int e = calc(a, size-1);
if(e%2==0)
return e=e+0; //return even
return sum;
}
int main( )
{
int a[6]={1,2,3,5,6,2};
int size = 6;
cout<< calc(a, size)<<endl;
system("pause");
return 0;
}
推荐答案
// calc(): returns sum(a[0], a[2], a[4], ...) - sum(a[1], a[3], a[5], ...)
int calc(int *a, int size)
{
int sum_even_pos = 0;
int sum_odd_pos = 0;
for (int i = 0; i < size; i++)
{
sum_even_pos += a[i];
if (++i < size) sum_odd_pos += a[i];
}
return sum_even_pos - sum_odd_pos;
}
这篇关于如何添加数组的偶数和奇数的和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!