在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
求最值和平均最简单的方法 循环遍历数组 /// <summary> /// 最值平均类 /// </summary> class MaxAveMin { private int[] intArray; public int maxValue; public int minValue; public int aveValue; public int total; public MaxAveMin(int[] array) { this.intArray = array; this.maxValue = intArray[0]; this.minValue = intArray[0]; this.aveValue = intArray[0]; } public int GetAverage() { for (int i = 0; i < intArray.Length; i++) { total += intArray[i]; } this.aveValue = total / intArray.Length; return this.aveValue; } public int GetMaxValue() { for (int i = 0; i < intArray.Length; i++) { if (this.maxValue < intArray[i]) this.maxValue = intArray[i]; } return this.maxValue; } public int GetMinValue() { for (int i = 0; i < intArray.Length; i++) { if (this.minValue > intArray[i]) this.minValue = intArray[i]; } return this.minValue; } } 使用排序(插入/选择/冒泡) /// <summary> /// 插入排序 /// </summary> public void InsertSort() { for (int i = 1; i < intArray.Length; i++) { //将第i个数插入到0到i-1的有序队列中 if (intArray[i] < intArray[i - 1]) { int temp = intArray[i]; int j = 0; //依次比较 for (j = i - 1; j >= 0 && temp < intArray[j]; j--) { intArray[j + 1] = intArray[j]; } intArray[j+1] = temp; } } } /// <summary> /// 冒泡排序 /// </summary> public void BubbleSort() { int temp; bool exchange;//交换标识 for (int i = 1; i < intArray.Length; i++) { //最多做n-1趟排序 exchange = false; for (int j = 0; j < intArray.Length - i; j++) { if (intArray[j] > intArray[j + 1]) { temp = intArray[j + 1]; intArray[j + 1] = intArray[j]; intArray[j] = temp; exchange = true; } if (!exchange) return; } } } /// <summary> /// 选择排序 /// </summary> public void SelectSort() { int i, j, k, temp; for (i = 0; i < intArray.Length; i++) { //第i趟排序 从i到intArray.Length-1中选中最小的 k = i; for (j = i + 1; j < intArray.Length; j++) { if (intArray[j] < intArray[k]) k = j;//目前最小值的位置 } if (k != i) { //交换 temp = intArray[i]; intArray[i] = intArray[k]; intArray[k] = temp; } } } /// <summary> /// 通过排序算法获得最大值 /// </summary> /// <returns></returns> public int GetMaxValueBySort() { InsertSort(); //BubbleSort(); //SelectSort(); return intArray[intArray.Length - 1]; } 主函数 static void Main(string[] args) { //求最值,平均 int[] intArray; List<int> numList = new List<int>(); int i=5; while (i > 0) { Console.WriteLine("请输入1个整数:"); int num = Convert.ToInt32(Console.ReadLine()); numList.Add(num); i--; } intArray = numList.ToArray<int>(); MaxAveMin mam = new MaxAveMin(intArray); //int max = mam.GetMaxValue(); int max = mam.GetMaxValueBySort(); int min = mam.GetMinValue(); int ave = mam.GetAverage(); Console.WriteLine("最大值为{0}", max); Console.WriteLine("平均值为{0}", ave); Console.WriteLine("最小值为{0}", min); }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论