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

C# 考勤统计问题:仅将缺勤学生加入缺勤列表功能运行异常

代码修复说明

核心错误点

  • 出勤判断分支错误将出勤学生添加到了absent缺勤列表,导致所有学生最终都出现在缺勤列表中
  • 出勤分支未将学生姓名添加到present出勤列表,最终绿色打印部分无内容输出
  • 多余的Append()方法调用:List<T>的Append()是返回新序列的纯方法,不会修改原列表,无实际作用可直接删除
  • 额外冗余逻辑:foreach遍历已经拿到了每个学生对象,无需额外定义v变量做索引访问

修正后完整代码

using System;
using System.Collections.Generic;

namespace HelloWorld
{
    class Hello
    {
        static void Main(string[] args)
        {
            List<string> students = new List<string>(5)
            {
                "Obama Ojane",
                "Yarik Ze",
                "Allen O'neill",
                "Naveen Sharma",
                "Monica Rathbun",
                "David McCarter",
                "Zayne Pan",
                "Rah"
            };

            int abs = 0;
            int pres = 0;

            List<string> absent = new List<string>(5);
            List<string> present = new List<string>(5);

            foreach (string student in students)
            {
                Console.Write(student + ": ");
                string attendance = Console.ReadLine().ToLower(); // 兼容大小写输入
                if (attendance == "absent" || attendance == "abs" || attendance == "a")
                {
                    abs++; 
                    absent.Add(student);
                }
                else if (attendance == "present" || attendance == "pres" || attendance == "p")
                {
                    pres++;
                    present.Add(student);
                }
            }
            Console.WriteLine();
            Console.Clear();
            Console.WriteLine("total present: " + pres);
            Console.WriteLine("total absent: " + abs);
            Console.WriteLine("total students: " + (abs+pres));

            Console.ForegroundColor = ConsoleColor.Red;
            foreach (var absentStudent in absent)
            {
                Console.WriteLine(absentStudent);
            }

            Console.ForegroundColor = ConsoleColor.Green;
            foreach (var presentStudent in present)
            {
                Console.WriteLine(presentStudent);
            }
            
            // 重置控制台颜色,避免后续输出异常
            Console.ResetColor();
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 02:36:05