【发布时间】:2017-05-01 04:31:20
【问题描述】:
在我的程序中,我试图从整数列表中找到Mode。从逻辑上讲,我的程序是正确的。但是,当我尝试打印出Mode 时,我收到以下消息"Mode: System.Collections.Generic.List'1[System.Int32]。我期望打印的结果是“Mode: 2, 7”,因为这两个数字在整数列表中出现了 3 次。我在这里做错了什么?提前致谢。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mode
{
class Program
{
static void Main(string[] args)
{
Test();
}
static void Test()
{
int[] values = { 1, 6, 4, 7, 9, 2, 5, 7, 2, 6, 5, 7, 8, 1, 3, 8, 2 };
List<int> mode = new List<int>();
mode = Mode(values);
Console.WriteLine("Mode: {0}", mode);
Console.ReadLine();
}
static List<int> Mode(int[] values)
{
int[] sorted = new int[values.Length];
values.CopyTo(sorted, 0);
Array.Sort(sorted);
List<int> result = new List<int>();
var counts = new Dictionary<int, int>();
int max = 0;
foreach (int num in sorted)
{
if (counts.ContainsKey(num))
counts[num] = counts[num] + 1;
else
counts[num] = 1;
}
foreach (var key in counts.Keys)
{
if (counts[key] > max)
{
max = counts[key];
result.Add(max);
}
}
return result;
}
}
}
【问题讨论】: