标题: 求已知数组的平均值 [打印本页] 作者: duanhuilin 时间: 2012-11-2 11:53 标题: 求已知数组的平均值 int sum = 0;
int[] ary = new int[] { 1, 2, 3, 4, 6, 9 };
for (int i = 0; i < ary.Length; i++)
{
sum += ary[i];
}
int avg = sum / ary.Length;
this.TextBox1.Text = avg.ToString();作者: 郑鹏 时间: 2012-11-2 12:14
把已解决改成分享多好作者: 张静_90 时间: 2012-11-4 22:23
int sum = 0;
int[] ary = new int[] { 1, 2, 3,10, 4, 6, 9 };
for (int i = 0; i < ary.Length / 2; i++)
{
sum += ary[i];
sum += ary[ary.Length - i - 1];
}
if (ary.Length % 2 != 0)
{
sum += ary[ary.Length / 2 ];
}
int avg = sum / ary.Length;
this.TextBox1.Text = avg.ToString();
减少循环次数!作者: 武江英 时间: 2012-11-4 23:07
int sum = 0;
int[] ary = new int[] { 1, 2, 3, 4, 6, 9 };
if (ary.Length % 2 != 0)
{
sum = ary[ary.Length / 2];
}
for (int i = ary.Length/2-1; i >=0; i--)
{
sum += ary[i];
sum += ary[ary.Length - i - 1];
}
int avg = sum / ary.Length;
this.TextBox1.Text = avg.ToString();
从中间开始加的。循环条件是不同的