當前位置:成語大全網 - 新華字典 - c# 多個數取值問題

c# 多個數取值問題

給妳寫個函數: 調用的方法GetMaxCountNumAvg(1, 1, 1, 1, 2, 3, 2, 5)

private double GetMaxCountNumAvg(params double[] arr)

{

List<int> numcount = new List<int>();

//取得arr中各不相同的數,個數存入壹個字典中

Dictionary<double, int> kv = new Dictionary<double, int>();

foreach (double d in arr)

{

if (!kv.ContainsKey(d))

{

kv.Add(d, 1);

}

else

{

kv[d]++;

}

}

//取得各數的個數

foreach (int v in kv.Values)

{

numcount.Add(v);

}

//得到個數最多的數的個數

numcount.Sort();

int[] tmp = numcount.ToArray();

int maxcount = tmp[tmp.Length - 1];

//計算最終結果

double finaltotal = 0;

double finalcount = 0;

foreach (double k in kv.Keys)

{

if (kv[k] == maxcount)

{

finaltotal += k * maxcount;

finalcount += maxcount;

}

}

return finaltotal / finalcount;

}