【问题标题】:C# Finding the Mode [duplicate]C#寻找模式[重复]
【发布时间】: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;

        }
    }
}

【问题讨论】:

    标签: c# mode


    【解决方案1】:

    您正在尝试从没有自定义 .ToString() 实现的引用类型类中使用 string.Format 和对象。我推荐使用String.Join(参考here

    C#

    Console.WriteLine("Mode: {0}", String.Join(", ", mode));
    

    【讨论】:

      【解决方案2】:

      正确提及用户 DesertFox。 您正在尝试打印列表。除此之外,根据您的要求,使用String.Join 将其作为单个string

      如下修改你的测试方法

          static void Test()
          {
              try
              {
                  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}", String.Join(", ", mode));
                  Console.ReadLine();
              }
              catch(Exception ex)
              {
      
              }
          }
      

      输出

      【讨论】:

      • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
      【解决方案3】:

      打印列表中的项目而不是列表本身。

      【讨论】:

        猜你喜欢
        • 2017-08-17
        • 2012-06-21
        • 1970-01-01
        • 2018-03-07
        • 1970-01-01
        • 2021-10-04
        • 2022-06-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多