如何检查一个值在数组中出现的次数

本文关键字:数组 一个 何检查 检查 | 更新日期: 2023-09-27 17:57:51

所以这就是我希望输出的样子:

How many numbers? 10
Give number 1: 1
Give number 2: 3
Give number 3: 1
Give number 4: 3
Give number 5: 4
Give number 6: 6
Give number 7: 4
Give number 8: 8
Give number 9: 2
Give number 10: 1
Number 1 appeared 3 times
Number 2 appeared 1 times
Number 3 appeared 2 times
Number 4 appeared 2 times
Number 6 appeared 1 times
Number 8 appeared 1 times

问题是,我已经完成了读取用户输入的部分。然而,我不知道如何继续告诉每个数字出现了多少次的部分。

此外,我做这是一项作业,所以大部分代码都是芬兰语的。不过,我希望你仍然能理解。

using System;
namespace Ohjelma
{
    class Ohjelma
    {
        static void Main()
        {
            Console.Write("Kuinka monta lukua? ");
            int pituus = Convert.ToInt32(Console.ReadLine());
            int[] luvut = new int[pituus];

            for (int i = 0; i < pituus; i++)
            {
                Console.Write("Anna {0}. luku:", i + 1);
                luvut[i] = Convert.ToInt32(Console.ReadLine());
            }
            for (int i = 0; i < luvut.Length; i++)
            {
                Console.Write(luvut[i]);
            }
            Console.ReadLine();
        }
    }
}

编辑:很抱歉在它应该输出什么的示例中出现了代码块,即使我尝试过,也不确定如何使用块引号。谢谢

如何检查一个值在数组中出现的次数

您可以像一样使用LINQ

var query = luvut.GroupBy(r => r)
                .Select(grp => new
                {
                    Value = grp.Key,
                    Count = grp.Count()
                });

对于输出,您可以使用:

foreach (var item in query)
{
    Console.WriteLine("Value: {0}, Count: {1}", item.Value, item.Count);
}
int[] num = { 1, 1, 1, 3, 3, 4, 5, 6, 7, 0 };
int[] count = new int[10];
//Loop through 0-9 and count the occurances
for (int x = 0; x < 10; x++){
    for (int y = 0; y < num.Length; y++){
        if (num[y] == x)
            count[x]++;
    }
}
//For displaying output only            
for (int x = 0; x < 10; x++)
    Console.WriteLine("Number " + x + " appears " + count[x] + " times");

程序输出:

Number 0 appears 1 times
Number 1 appears 3 times
Number 2 appears 0 times
Number 3 appears 2 times
Number 4 appears 1 times
Number 5 appears 1 times
Number 6 appears 1 times
Number 7 appears 1 times
Number 8 appears 0 times

我理解当你所有的同学都完成了他们的任务,而你还在挣扎时的感觉有多糟糕。我的代码应该足够简单,便于您学习。

如果您不想使用LINQ,您可以按照以下方式进行编码:-

public class Program 
{
   public static void Main()
   {
       int[] arr1 = new int[] {1,3,3,5,5,4,1,2,3,4,5,5,5};
       List<int> listArr1 = arr1.ToList();
       Dictionary<int,int> dict1 = new Dictionary<int,int>();
       foreach(int i in listArr1)
       {
          if(dict1.ContainsKey(i))
          {
              int value  = dict1[i];
              value++;
              dict1[i]= value;
          }
          else
          {
              dict1.Add(i,1);
          }
       }
       for(int x = 0 ; x < dict1.Count(); x++)
       {        
          Console.WriteLine("Value {0} is repeated {1} times", dict1.Keys.ElementAt(x),dict1[dict1.Keys.ElementAt(x)]);                       
       }
   }
}