標籤:ogr ret 異常 img foreach for 個數 lin ons
C#擷取一個數組中的最大值、最小值、平均值1.給出一個數組
1 int[] array = new int[] { 1,2,4,3,0,-1,34,545,2,34};2.數組Array內建方法
本身是直接可以調用Min(),Max(),Average()方法來求出 最小值、最大值、平均值
1 Console.WriteLine("--------------Array自身方法-----------------");2 Console.WriteLine("Min:{0}",array.Min());3 Console.WriteLine("Max:{0}", array.Max());4 Console.WriteLine("Average:{0}", array.Average());輸出結果:
1 --------------Array自身方法-----------------2 Min:-13 Max:5454 Average:62.4
3.編碼實現最小值
1 /// <summary> 2 /// 最小值 3 /// </summary> 4 /// <param name="array"></param> 5 /// <returns></returns> 6 public static int Min(int[] array) 7 { 8 if (array == null) throw new Exception("數組空異常"); 9 int value = 0;10 bool hasValue = false;11 foreach (int x in array)12 {13 if (hasValue)14 {15 if (x < value) value = x;16 }17 else18 {19 value = x;20 hasValue = true;21 }22 }23 if (hasValue) return value;24 throw new Exception("沒找到");25 }最大值
1 /// <summary> 2 /// 最大值 3 /// </summary> 4 /// <param name="array"></param> 5 /// <returns></returns> 6 public static int Max(int[] array) 7 { 8 if (array == null) throw new Exception("數組空異常"); 9 int value = 0;10 bool hasValue = false;11 foreach (int x in array)12 {13 if (hasValue)14 {15 if (x > value)16 value = x;17 }18 else19 {20 value = x;21 hasValue = true;22 }23 }24 if (hasValue) return value;25 throw new Exception("沒找到");26 }平均值
1 /// <summary> 2 /// 平均值 3 /// </summary> 4 /// <param name="source"></param> 5 /// <returns></returns> 6 public static double? Average(int[] array) 7 { 8 if (array == null) throw new Exception("數組空異常"); 9 long sum = 0;10 long count = 0;11 checked12 {13 foreach (int? v in array)14 {15 if (v != null)16 {17 int a = v.GetValueOrDefault();18 sum += v.GetValueOrDefault();19 count++;20 }21 }22 }23 if (count > 0) return (double)sum / count;24 return null;25 }4.測試輸出測試代碼
1 static void Main(string[] args) 2 { 3 int[] array = new int[] { 1,2,4,3,0,-1,34,545,2,34}; 4 5 Console.WriteLine("--------------Array自身方法-----------------"); 6 Console.WriteLine("Min:{0}",array.Min()); 7 Console.WriteLine("Max:{0}", array.Max()); 8 Console.WriteLine("Average:{0}", array.Average()); 9 10 Console.WriteLine("---------------內部實現方法------------------");11 int min = Program.Min(array);12 int max = Program.Max(array);13 double? average = Program.Average(array);14 Console.WriteLine("Min:" + min);15 Console.WriteLine("Max:" + max);16 Console.WriteLine("Average:" + average);17 Console.Read();18 }輸出結果
以上代碼也是從.NET Framework中摘出來的,實際上 Array的內建求最大值、最小值、平均值的演算法就是這樣做的,在.NET Framework源碼中可以看到
C#擷取一個數組中的最大值、最小值、平均值