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

使用并行数组匹配学生姓名与分数问题:C#代码调试

修复并行数组的学生姓名与分数匹配问题

我来帮你搞定这个问题!你的代码核心问题是错误地使用排序打乱了学生姓名和分数的原始对应关系,而且筛选后的分数数组和原姓名数组长度不匹配,导致输出时完全对应不上。

原代码的问题分析

  • 你先执行了Array.Sort(studentNames, classScores),这一步会把姓名按字母序排序,分数按大小序排序,直接破坏了原本一一对应的姓名-分数配对关系。
  • 接着又尝试对studentNames和筛选后的Lessthan40Array排序,这不仅没必要,还因为Lessthan40Array的长度可能比studentNames短,后续按索引访问会出现逻辑错误。
  • 最后循环输出时,用studentNames[i]对应Lessthan40Array[i],但这两个数组的元素已经没有任何关联了,自然会显示错误的配对结果。

解决方案1:用LINQ简洁实现(推荐)

利用LINQ的Zip方法可以轻松把两个并行数组的元素一一配对,筛选后直接输出,完美保留对应关系:

static void Main(string[] args)
{
    int[] classScores = new int[5];
    string[] studentNames = new string[5];

    // 收集用户输入的学生姓名和分数
    for (int i = 0; i < studentNames.Length; i++)
    {
        Console.WriteLine("Please enter a Student Name.");
        studentNames[i] = Console.ReadLine();
        Console.WriteLine("Please enter marks.");
        classScores[i] = Convert.ToInt32(Console.ReadLine());
    }

    // 关联姓名与分数,筛选分数≤40的学生
    var lowScoreStudents = studentNames
        .Zip(classScores, (name, score) => new { Name = name, Score = score })
        .Where(item => item.Score <= 40);

    // 输出结果
    Console.WriteLine("\nStudents with score ≤ 40:");
    foreach (var student in lowScoreStudents)
    {
        Console.WriteLine($"{student.Name} : {student.Score}");
    }

    Console.ReadKey();
}

解决方案2:基础循环实现(适合新手理解)

如果还没接触LINQ,直接遍历数组索引,检查对应位置的分数是否符合条件即可,完全保留原始配对:

static void Main(string[] args)
{
    int[] classScores = new int[5];
    string[] studentNames = new string[5];

    // 收集用户输入的学生姓名和分数
    for (int i = 0; i < studentNames.Length; i++)
    {
        Console.WriteLine("Please enter a Student Name.");
        studentNames[i] = Console.ReadLine();
        Console.WriteLine("Please enter marks.");
        classScores[i] = Convert.ToInt32(Console.ReadLine());
    }

    // 遍历筛选并输出符合条件的学生
    Console.WriteLine("\nStudents with score ≤ 40:");
    for (int i = 0; i < studentNames.Length; i++)
    {
        if (classScores[i] <= 40)
        {
            Console.WriteLine($"{studentNames[i]} : {classScores[i]}");
        }
    }

    Console.ReadKey();
}

关键提醒

并行数组的核心逻辑是相同索引对应同一组数据,所以绝对不能单独对其中一个数组排序,或者打乱索引的对应关系。如果后续需要排序(比如按分数排序输出),一定要使用Array.Sort(keys, values)的重载,保证两个数组的索引同步调整,但在这个需求里完全不需要排序操作,直接筛选即可。

内容的提问来源于stack exchange,提问作者FeatDavid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:49:06