C#二维数组实现10组姓名GWA录入并按最高GWA排序问题求助
原代码错误点
- 使用的矩形二维数组(
string[,])不支持Array.Sort默认方法,直接调用会触发运行时异常 - 循环条件
i <= 10存在索引越界风险,长度为10的数组索引范围为0~9,循环条件应改为i < 10 - 仅调用
Console.ReadLine()未将输入内容存入二维数组,导致数组全为默认空值 - GWA为数值类型,直接以字符串形式排序会按照字符编码顺序计算,无法得到正确的数值大小排序结果
修正后可运行代码
namespace ConsoleApp8 { class Program { static void Main(string[] args) { // 二维数组定义:10行存储10个学生,2列分别存储姓名、GWA string[,] g = new string[10, 2]; Console.WriteLine("Names and their Prelim GWA: "); // 录入10组学生信息 for (int i = 0; i < 10; i++) { Console.Write($"请输入第{i+1}个学生姓名:"); g[i, 0] = Console.ReadLine(); Console.Write($"请输入第{i+1}个学生的GWA:"); g[i, 1] = Console.ReadLine(); } // 自定义冒泡排序实现按GWA从高到低排序 for (int i = 0; i < g.GetLength(0) - 1; i++) { for (int j = 0; j < g.GetLength(0) - 1 - i; j++) { // 转换为double类型做数值比较 double currentGwa = double.Parse(g[j, 1]); double nextGwa = double.Parse(g[j + 1, 1]); if (currentGwa < nextGwa) { // 交换两行的姓名和GWA string tempName = g[j, 0]; g[j, 0] = g[j + 1, 0]; g[j + 1, 0] = tempName; string tempGwa = g[j, 1]; g[j, 1] = g[j + 1, 1]; g[j + 1, 1] = tempGwa; } } } // 输出排序结果 Console.WriteLine("\n按GWA从高到低排序结果:"); for (int i = 0; i < g.GetLength(0); i++) { Console.WriteLine($"姓名:{g[i, 0]} \t GWA:{g[i, 1]}"); } Console.ReadKey(); } } }
实现说明
- 全程使用二维数组完成需求,没有引入额外的数据结构
- 冒泡排序逻辑简单易懂,适合初学者理解二维数组的排序实现
- 排序前将GWA转换为数值类型比较,保证排序结果符合数值大小规则
- 补充了输入提示和排序结果输出逻辑,交互更清晰
内容的提问来源于stack exchange,提问作者Dean
相关产品推荐
相关产品推荐

