如何检查一个值在数组中出现多少次? [英] How to check how many times a value appears in an array?

查看:55
本文介绍了如何检查一个值在数组中出现多少次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So this is what I want my output to look like:

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

问题是,我已经完成了读取用户输入的部分.但是,我不知道如何继续讲述每个数字出现了多少次的部分.

The thing is, I've got the part which reads the user input done. However, I have no idea how to continue with the part which tells how many times each number appeared.

此外,我正在做功课,因此大多数代码都使用芬兰语.我希望您仍然能够理解它.

Also, I'm doing this as a schoolwork so most of the code is in Finnish. I hope you can still understand it, though.

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();
        }
    }
}

很抱歉代码块应该输出什么示例,即使我尝试过,也不能完全确定如何使用代码块引用.谢谢!

Sorry about the code block on the example of what it should output, not exactly sure how to use blockquotes even though I tried. Thanks!

推荐答案

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

我知道当您所有的同学都完成了自己的学习之后,您仍在苦苦挣扎的感觉.我的代码应该足够简单以供您学习.

I understand how bad it feels when all your classmates had finish theirs, and you are still struggling. My codes should be simple enough for your learning.

这篇关于如何检查一个值在数组中出现多少次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆