C#——求若干數的最大值最小值和平均值
阿新 • • 發佈:2019-02-08
/* (程式頭部註釋開始)
* 程式的版權和版本宣告部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 檔名稱:編寫一個控制檯應用。輸入一組整數,輸出最大值、最小值和平均值。
* 程式的版權和版本宣告部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 檔名稱:編寫一個控制檯應用。輸入一組整數,輸出最大值、最小值和平均值。
* 作 者: 李莉* 完成日期: 2016年 04月 08 日
* 版 本 號: V1.0
* 對任務及求解方法的描述部分
* 輸入描述:
* 問題描述:
* 程式輸出:
* 程式頭部的註釋結束
*/
程式程式碼:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("請您輸入一組整數,中間用逗號隔開:"); String str = Console.ReadLine(); String[] s = str.Split(','); int[] b = new int[s.Length]; for (int i = 0; i < s.Length; ++i) { b[i] = int.Parse(s[i]); } Myclass c = new Myclass(); c.get_number(b); } } class Myclass { public void get_number(params int[] a) { int i = 0; int max = a[0]; int min = a[0]; double sum = 0, ever = 0; for (i = 0; i < a.Length; i++) { if (max < a[i]) max = a[i]; if (min > a[i]) min++; sum += a[i]; } ever = (sum - min - max) / (a.Length - 2); Console.WriteLine("最大數:{0},", max); Console.WriteLine("最小數:{0},", min); Console.WriteLine("平均值:{0},", ever); Console.ReadKey(); } } }
執行結果:
心得體會:
上次很糾結的是如何規定陣列的長度,於是開始的方案是設定的陣列長度很長,然後輸入的時候利用特別的符號讓輸入迴圈停止,但是發現那種方法實現比較複雜,於是在看了一位學長處理不固定長度的陣列後恍然大悟,原來看可以這樣子操作,然後就有了現在的這個程式。
本程式解釋:
這個程式本意是先輸入的數字是以字串的形式的,然後中間用逗號隔開,定義一個和輸入字串等長的int型陣列,把字串裡面的元素複製給int型的陣列,然後進行運算。