日期:2014-05-18  浏览次数:21221 次

C# 数组求和
int [] Tel = new int[6];
Tel[0]=12;
Tel[1]=16;
Tel[2]=43;
Tel[3]=665;
Tel[4]=23;
Tel[5]=1;
将该数组分两组求和 将结果存入ArrayList中,
如Tel [0] +Tel [2]+ Tel [4]=12+43+23=78
  Tel [1] +Tel [3]+ Tel [5]=16+665+1=682
这里不是奇数偶数 关系 是隔2个相加 也有可能数组更长 隔得是3,4,5
用循环


------解决方案--------------------
C# code
 private void button2_Click(object sender, EventArgs e)
        {
            int _index = 2;//相隔几位数
            int[] Tel = new int[6];
            Tel[0] = 12;
            Tel[1] = 16;
            Tel[2] = 43;
            Tel[3] = 665;
            Tel[4] = 23;
            Tel[5] = 1;
            
            ArrayList arrlist = new ArrayList();
            for (int i = 0; i < 2; i++)
            {
                arrlist.Add(Sum(Tel,_index,i));
            }
            foreach (var item in arrlist)
            {
                MessageBox.Show(item.ToString());
            }
        }

        private int Sum(int[] tel,int _index,int starIndex)
        {
            int sum = 0;
            for (int i = starIndex; i < tel.Length; i += _index)
            {
                sum += tel[i];
            }
            return sum;
        }