c#通過鍵盤輸入若干個整數,長度不得多於20個,最後將其中最大的數輸出,採用控制檯的形式實現。

通過鍵盤輸入若干個整數,長度不得多於20個,最後將其中最大的數輸出,採用控制檯的形式實現。
思路:從鍵盤上輸入連續的數字,採用空格隔開,對輸入的數字的數量計算,超過20不進行計算最大值,小於20則進行計算最大值。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace mashufang

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("請輸入少於20個數字:");

            int n;

            string inputStr = Console.ReadLine();        //讀輸入的多個連續數字

            string[] numsStr = inputStr.Split(' ');   //用空格分割字符串

            n = numsStr.Count();

            int[] nums = new int[n];

            if (n >20)

            {

                Console.WriteLine("您輸入的數字超過20個,請重新輸入:");

            }

            else

            {

                for (int i = 0; i < n; i++)

                {

                    nums[i] = int.Parse(numsStr[i]);     //字符串轉數字

                }

                //輸出

                for (int i = 0; i < n; i++)

                {

                    if (nums[0] < nums[i])

                    {

                        nums[0] = nums[i]

                    }

                }

                Console.WriteLine("最大值是:{0}", nums[0]);

            } 

            Console.ReadKey();

        }

    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章