冒泡排序:由大到小排列
int[] shuzu = new int[] { 3, 1, 8, 4, 0, 5, 6 }; for (int i = 0; i < 7; i++) { for (int j = i; j < 6; j++) { if (shuzu[i] < shuzu[j + 1]) { zhong = shuzu[i]; shuzu[i] = shuzu[j + 1]; shuzu[j + 1] = zhong; } } } for (int i = 0; i < 7; i++) { Console.WriteLine(shuzu[i]); } Console.ReadLine();
用foreach代替:
int[] shuzu = new int[] { 3, 1, 8, 4, 0, 5, 6 }; for (int i = 0; i < 7; i++) { for (int j = i; j < 6; j++) { if (shuzu[i] < shuzu[j + 1]) { zhong = shuzu[i]; shuzu[i] = shuzu[j + 1]; shuzu[j + 1] = zhong; } } } foreach (int a in shuzu)//遍历数组 { Console.WriteLine(a); } Console.ReadLine();
例题:
//输入人数,输入每个人的成绩 //需要最高分、最低分 //去掉两个最高分,去掉两个最低分,求平均分。 Console.Write("请输入班级人数:"); int a = int.Parse(Console.ReadLine()); double[]fen=new double[a]; for (int i=0;i<a;i++ ) { Console.Write("请输入第"+(i+1)+"个人的成绩"); fen[i] = double.Parse(Console.ReadLine()); } double zhong; for (int i = 0; i < a; i++) { for (int j = i; j < a-1; j++) { if (fen[i] < fen[j + 1]) { zhong = fen[i]; fen[i] = fen[j + 1]; fen[j + 1] = zhong; } } } Console.WriteLine("最高分是"+fen[0]); Console.WriteLine("最低分是" + fen[a-1]); double sum = 0; for (int i=2;i<a-2 ; i++) { sum+=fen[i]; } Console.WriteLine("平均分是"+sum/(a-4)); Console.ReadLine();
时间: 2024-12-29 06:46:13