You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:45:03