获取这5个数据合的平均值~!
   ProfitRate1,ProfitRate2,ProfitRate3,ProfitRate4,ProfitRate5.
    如果某个数为0 的时候就不计算它,例如:如果ProfitRate3为0 的话就只计算其他4个的平均值~!
我写的方法是每个字段都要判断是否为0 ,然后相加取平均值,代码很长,我想知道有没有更简单的写法。
 能减少代码的长度。
---------
 
      
     

解决方案 »

  1.   

    float avgRate=(ProfitRate1+ProfitRate2+ProfitRate3+ProfitRate4+ProfitRate5)/((ProfitRate1==0?0:1)+(ProfitRate2==0?0:1)+(ProfitRate3==0?0:1)+(ProfitRate4==0?0:1)+(ProfitRate5==0?0:1))
      

  2.   

    using System;
    using System.Collections.Generic;
    using System.Text;namespace ConsoleApplication17
    {
        class Program
        {
            static void Main(string[] args)
            {
                System.Data.DataTable dt = new System.Data.DataTable();
                dt.Columns.Add("value", typeof(int));
                AddRow(dt,1);
                AddRow(dt, 2);
                AddRow(dt, 0);
                AddRow(dt, 3);            double d = Convert.ToDouble(dt.Compute("sum(value)", "").ToString()) / Convert.ToDouble(dt.Compute("count(value)", "value>0").ToString());            Console.WriteLine(d);
                Console.Read();
                
            }
            static void AddRow(System.Data.DataTable dt ,int i)
            {
                System.Data.DataRow dRow = dt.NewRow();
                dRow["value"] = i;
                dt.Rows.Add(dRow);
            }
        }
    }
      

  3.   

    每列取2 次  ,1次是值 一次是  flag, 然后把值求和除以flag的和。比如说:ProfitRate1,flag1,
    如果 ProfitRate1 为0时 flag1,为0
    如果 ProfitRate1 不为0时 flag1,为1;最后用 ProfitRate1,ProfitRate2,ProfitRate3,ProfitRate4,ProfitRate5. 的和 除以flag1,flag2,flag3,flag4,flag5的和不知道能不能实现。参考下吧。
      

  4.   

    codefloatavgRate=(ProfitRate1+ProfitRate2+ProfitRate3+ProfitRate4+ProfitRate5)/((ProfitRate1==0?0:1)+(ProfitRate2==0?0:1)+(ProfitRate3==0?0:1)+(ProfitRate4==0?0:1)+(ProfitRate5==0?0:1))