阵列中的最大和最小数 [英] Largest and smallest number in an array

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

问题描述

这完美的作品......但是当我使用的foreach 为而不是这不作品。我无法理解的foreach 相同。

 命名空间ConsoleApplication2
{
    类节目
    {
        静态无效的主要(字串[] args)
        {
            INT []数组=新INT [10];
            Console.WriteLine(请输入数组元素到B分类);
            的for(int i = 0;我小于10;我++)
            {
                数组[我] = Convert.ToInt32(到Console.ReadLine());
            }
            诠释最小=阵列[0];
            的for(int i = 0;我小于10;我++)            {
                如果(阵列[1] - ;最小)
                {
                    最小=阵列[我]                }
            }
            诠释最大=阵列[9];
            的for(int i = 0;我小于10;我++)
            {                如果(阵列[I]>最大)
                {
                    最大=阵列[我]                }
            }
            Console.WriteLine(最小没有为{0},最小的);
            Console.WriteLine(最大的无是{0},最大的);
            Console.Read();
        }
    }
}


解决方案

为什么你不使用此?

  INT []数组= {12,56,89,65,61,36,45,23};
INT最大= array.Max();
INT分钟= array.Min();

This works perfectly...but when I use foreach instead of for this doesn't works. I can't understand for and foreach are same.

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[10];
            Console.WriteLine("enter the array elements to b sorted");
            for(int i=0;i<10;i++)
            {
                array[i] = Convert.ToInt32(Console.ReadLine());
            }
            int smallest = array[0];
            for(int i=0;i<10;i++)

            {
                if(array[i]<smallest)
                {
                    smallest=array[i];

                }
            }
            int largest = array[9];
            for(int i=0;i<10;i++)
            {

                if (array[i] > largest)
                {
                    largest = array[i];

                }
            }
            Console.WriteLine("the smallest no is {0}", smallest);
            Console.WriteLine("the largest no is {0}", largest);
            Console.Read();


        }
    }
}

解决方案

Why are you not using this?

int[] array = { 12, 56, 89, 65, 61, 36, 45, 23 };
int max = array.Max();
int min = array.Min();

这篇关于阵列中的最大和最小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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