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

控制台多维数组存学生成绩问题:循环存成绩失败,需嵌套循环吗?

解决方法:用嵌套循环实现学生成绩的多维数组存储

嘿,你说得没错,确实需要嵌套循环来搞定这个问题!因为你要给每个学生录入多门考试成绩,外层循环负责遍历每一位学生,内层循环则专门收集当前学生的所有成绩,这样才能把每一组数据准确存入多维数组中。

先看看你原来的代码片段(我帮你补全了缺失的部分):

Console.WriteLine("How many students will you be grading?");
string totalStudents = Console.ReadLine();
int studentSum = Convert.ToInt32(totalStudents);
Console.WriteLine(string.Empty);
Console.WriteLine("How many test scores will you enter for each student?");
string totalScores = Console.ReadLine();
int scoreSum = Convert.ToInt32(totalScores);

这段代码只完成了“获取数量”的第一步,缺少多维数组初始化和循环录入成绩的核心逻辑,所以成绩没法存进数组里。

下面是完整的可运行代码,我加了详细的注释:

Console.WriteLine("How many students will you be grading?");
string totalStudents = Console.ReadLine();
int studentSum = Convert.ToInt32(totalStudents);
Console.WriteLine(string.Empty);
Console.WriteLine("How many test scores will you enter for each student?");
string totalScores = Console.ReadLine();
int scoreSum = Convert.ToInt32(totalScores);

// 初始化多维数组:行=学生数,列=每个学生的成绩数
int[,] studentScores = new int[studentSum, scoreSum];

// 外层循环:遍历每一位学生
for (int i = 0; i < studentSum; i++)
{
    Console.WriteLine($"\n--- 录入第 {i+1} 位学生的成绩 ---");
    // 内层循环:遍历当前学生的每一门成绩
    for (int j = 0; j < scoreSum; j++)
    {
        Console.Write($"请输入第 {j+1} 门成绩:");
        // 读取成绩并转换为int,存入数组对应位置
        studentScores[i, j] = Convert.ToInt32(Console.ReadLine());
    }
}

// 可选:验证存储结果,打印所有学生的成绩
Console.WriteLine("\n--- 所有学生成绩如下 ---");
for (int i = 0; i < studentSum; i++)
{
    Console.Write($"第 {i+1} 位学生:");
    for (int j = 0; j < scoreSum; j++)
    {
        Console.Write($"{studentScores[i, j]} ");
    }
    Console.WriteLine();
}

关键逻辑说明:

  • 多维数组初始化:int[,] studentScores = new int[studentSum, scoreSum]; 这里第一个维度对应学生索引,第二个维度对应该学生的成绩索引。
  • 嵌套循环的分工:外层循环i控制当前处理的学生,内层循环j负责收集该学生的每一门成绩,把输入的值直接赋值给studentScores[i, j],这样就能精准存储每一条数据了。
  • 最后验证打印的部分可以帮你确认成绩是否正确存入数组,方便调试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:24:06