从连续的int数组元素创建对值
本文关键字:创建 数组元素 int 连续 | 更新日期: 2023-09-27 17:57:58
我需要求和一个数组中的第一个和第二个元素,然后是第三个和第四个元素,最后是第五个和第六个元素。例如,如果我得到作为输入的int[]{1,2,0,3,4,-1},我需要将其计算为新的int[]{3,3,3}
using System;
class Program
{
static void Main()
{
int[] Arr = new int[] {1, 2, 0, 3, 4, -1};
int sum = 0;
foreach(int index in Arr)
{
//sum = (Arr[index at 0 position] + Arr[item at 0 position + 1]);
//Then do nothing with Arr[index at 1 position]
//Then sum Arr[index at 2 position] + Arr[item at 3 position];
//Then do nothing with Arr[index at 4 position]
//if I test this condition
// if(Arr[index]%2==0) //here I want to test the actual index of the element, not the value behind the index
//{skip the next Arr[index]}
//else{ sum Arr[index]+Arr[index + 1] }
}
}
}
这将对每一对进行求和,如果长度为奇数,则保留最后一对:
int[] Arr = new int[] { 1, 2, 0, 3, 4 };
int ExactResultLength = (int)(((double)Arr.Length / 2) + 0.5);
int[] res = new int[ExactResultLength];
int j = 0;
for (int i = 0; i < Arr.Length; i+= 2)
{
if(i + 1 < Arr.Length)
res[j] = Arr[i] + Arr[i+1];
else
res[j] = Arr[i];
j++;
}
假设您不关心没有配对的元素:
int[] Arr = new int[] {1, 2, 0, 3, 4, -1};
int[] Arr2 = new int[Arr.Length / 2];
for (int i = 0; i < Arr2.Length; i++)
Arr2[i] = Arr[i * 2] + Arr[i * 2 + 1];
但是,如果您这样做了,并且它应该出现在输出数组中,请在末尾添加以下行:
Arr2[Arr2.Length - 1] = Arr[Arr.Length - 1];
并将Arr2
的长度更改为Arr.Lenght / 2 + 1