如何用递归来算平均数呢?

huguosheng_89412 2012-02-13 05:44:25
中国 12
上海 6
徐汇 6
华山路 8
淮海西路 4
江苏 15
南京 20
昆山 10

湖南 15


首先地区级别是不固定的,数字也是不固定的
其次如果有子级,本级的平均数是子级的总和除以个数得到平均数
如何用递归来算平均数呢?
...全文
215 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
huangwenquan123 2012-02-14
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 huguosheng_89412 的回复:]
感谢huangwenquan123的回答,
但你的只是求了第一级的得分及平均数,那下面的第二级。。。。一直到最后第二级的的平均数急得分呢?
[/Quote]你在递归时在分别获取不同级数pid,在加进去到Dictionary中!
huguosheng_89412 2012-02-14
  • 打赏
  • 举报
回复
感谢huangwenquan123的回答,
但你的只是求了第一级的得分及平均数,那下面的第二级。。。。一直到最后第二级的的平均数急得分呢?

huangwenquan123 2012-02-14
  • 打赏
  • 举报
回复
只写了个大概。

public class City
{
public string Name { get; set; }
public int CID { get; set; }
public int PID { get; set; }
public int Score { get; set; }
}
public static void GetAll(IEnumerable<City> list, int PID, Dictionary<int, int> d, Dictionary<int, int> count)
{
IEnumerable<City> l = list.Where(x => x.PID == PID);
foreach (City c in l)
{
if (c.PID == 0)
{
d.Add(c.CID, c.Score);
count.Add(c.CID, 1);
}
else
{
if (!d.ContainsKey(c.PID))
{
int resultID = -1;
GetParent(list, c.PID, ref resultID);
if (resultID != -1)
{
d[resultID] += c.Score;
count[resultID] += 1;
}
}
else
{
d[c.PID] += c.Score;
count[c.PID] += 1;
}

}
GetAll(list, c.CID, d, count);
}
}
public static void GetParent(IEnumerable<City> ie, int PID, ref int ResultID)
{
City c = ie.Where(x => x.CID == PID).First();
if (c != null)
{
if (c.PID == 0)
ResultID = c.CID;
else
GetParent(ie, c.PID, ref ResultID);
}

}
static void Main(string[] args)
{
List<City> list = new List<City>(){
new City(){Name="中国",CID=1,PID=0,Score=1},new City(){Name="上海",CID=2,PID=1,Score=2},new City(){Name="北京",CID=3,PID=1,Score=3},
new City(){Name="徐汇",CID=8,PID=2,Score=8},new City(){Name="莲花路",CID=9,PID=8,Score=11},
new City(){Name="小日本",CID=4,PID=0,Score=4},new City(){Name="东京",CID=5,PID=4,Score=5},
new City(){Name="东京塔",CID=10,PID=5,Score=10},
new City(){Name="美国",CID=6,PID=0,Score=6},new City(){Name="纽约",CID=7,PID=6,Score=7},
new City(){Name="中央公园",CID=11,PID=7,Score=11}};
Dictionary<int, int> dic = new Dictionary<int, int>();
Dictionary<int, int> count = new Dictionary<int, int>();
GetAll(list, 0, dic, count);
foreach (KeyValuePair<int, int> k in dic)
{
Console.WriteLine("CID:{0} 得分:{1} 平均数:{2}", k.Key, k.Value, k.Value / count[k.Key]);
}
}
/*
CID:1 得分:25 平均数:5
CID:4 得分:19 平均数:6
CID:6 得分:24 平均数:8
*/
hetengfei_ 2012-02-13
  • 打赏
  • 举报
回复
foreach 编历求总数!/this.count
AAACCCEEEFFFA 2012-02-13
  • 打赏
  • 举报
回复
能递归?这都没有规律。

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧