如何找到数组的最小和最大元素?

时间:2016-04-14 18:32:57

标签: c#

private void button1_Click(object sender, EventArgs e)
{
    int[] m = new int[1000];
    int n = textBox1.Lines.Lenght;
    int i;
    int k = 0;
    int sum = 0;
    int product = 1;
    int average = 0;

    for (i = 0; i < n; i++)
    {
        try 
        {
            m[k] = Convert.ToInt32(textBox1.Lines[i]);
            sum = sum + m[k];
            product = product * m[k];
            average = sum / n;
        }     
        catch 
        {
            MessangeBox.Show("Буквы нельзя!!");
            k++;
        }
    }

    label10.Text = n.ToString();
    label11.Text = sum.ToString();
    label12.Text = product.ToString();
    label13.Text = average.ToString();     
}

2 个答案:

答案 0 :(得分:1)

using System;

using System.Collections.Generic;

using System.Linq;



int[] m = new int[1000];

// fill in the array here .....

int min = m.Min(); // find the minimum

int max = m.Max(); // find the maximum

答案 1 :(得分:1)

以下内容应该有所帮助:

private void button1_Click(object sender, EventArgs e)
{
    int[] m = new int[1000];
    int n = textBox1.Lines.Lenght;
    int i;
    int k = 0;
    int sum = 0;
    int product = 1;
    int average = 0;
    int min = Int32.MaxValue;   // will hold min value
    int max = Int32.MinValue;   // will hold max value

    for (i = 0; i < n; i++)
    {
        try 
        {
            m[k] = Convert.ToInt32(textBox1.Lines[i]);
            sum = sum + m[k];
            product = product * m[k];
            if (m[k] < min)
              min = m[k];
            if (m[k] > max)
              max = m[k];
        }     
        catch 
        {
            MessageBox.Show("Буквы нельзя!!");
            k++;
        }
    }
    average = sum / n;  //Computing average here is more efficient
    label10.Text = n.ToString();
    label11.Text = sum.ToString();
    label12.Text = product.ToString();
    label13.Text = average.ToString();     
}

警告:如果您的数组为空,您可能不希望将Int32.MaxValue和Int32.MinValue作为默认的最小值和最大值。您将需要单独处理该案例。