C#从数组中获取最小值 [英] c# get the min value from array

查看:68
本文介绍了C#从数组中获取最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在从数组中获取最小值.每次运行时,最小值仍为零.我知道索引必须减一,但我只是不知道如何将其应用于代码.对不起,我的英语不好,希望大家能帮帮我!

I'm getting stuck on getting min value from array. every time when I run it, the minimum value is still zero. I know that the index has to go to minus one, but i just don't know how should I apply it on the code. sorry for my poor English, I hope you guys can help me out!

public partial class Form1 : Form
{
    int[] numbers = new int[99];
    int index = 0;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
    public int Som()
    {
        //if the numbers are <99 they will be add to index.
        int som = 0;
        for (int i = 0; i < 99; i++)
        {
            som = som + numbers[i];
        }
        return som;
    }
    public int Average()
    {
        // 
        int answersom = Som();
        int g = (answersom / index);
           return g;     
    }
    public int Max()
    {
        int Max = numbers[0];
        foreach (int number in numbers)
        {
            if (number > Max)
            {
                Max = number;
            }
        }
        return Max;
    }
    public int Min()
        {// array gets de value thats on 0
            int Min = numbers[0];
            foreach (int number in numbers)
            {// if the number is smaller then 0.
                if (number < Min)
                {// zero is the new number
                    Min = number;
                }

            }
            return Min;
        }
    private void button1_Click(object sender, EventArgs e)
    {
        //if textbox doesnt contain numbers
        if (textBox1.Text.All(chr => char.IsLetter(chr)))
        {
            //labeltext message 'please only fill in numbers'
            label1.Text = "Vul alleen Cijfers in";
        }
        //else
        else
        {
            //is putting the numbers on the right spot of the array
            numbers[index] = Convert.ToInt32(textBox1.Text);
            //index will add each time.
            index++;
            label4.Text = Convert.ToString(Som());

        }
        //
        int g = Convert.ToInt32(textBox1.Text);
        label5.Text = Convert.ToString(Average());
        {

            label6.Text = Convert.ToString(Min());

            label7.Text = Convert.ToString(Max());

        }
    }
}

}

推荐答案

您可以轻松地使用Linq,

You can easily use with Linq,

使用System.Linq;

Using System.Linq;

int min = numbers.Min();

这篇关于C#从数组中获取最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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