How to get the second highest number in an array in Visual C#?

后端 未结 9 1798
误落风尘
误落风尘 2020-12-17 05:40

I have an array of ints. I want to get the second highest number in that array. Is there an easy way to do this?

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 05:56

        static void Main(string[] args)
        {
            int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5,12,11,14 };
            int num1 = 0, temp = 0;
            for (int i = 0; i < myArray.Length; i++)
            {
                if (myArray[i] >= num1)
                {
                    temp = num1;
                    num1 = myArray[i];
                }
                else if ((myArray[i] < num1) && (myArray[i] > temp))
                {
                    temp = myArray[i];
                }
            }
            Console.WriteLine("The Largest Number is: " + num1);
            Console.WriteLine("The Second Highest Number is: " + temp);
            Console.ReadKey();
        }
    

提交回复
热议问题