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

如何在C#中为数值二维数组添加字符串标签并格式化输出

解决带标签的二维数组格式化输出问题

你的代码核心问题是标签输出顺序错误:先把所有垂直标签(星期)一次性输出完,再输出水平标签(时间),最后才输出数组,完全打乱了布局。正确的逻辑应该是:

  1. 先输出顶部的水平标签,前面要留空对应左侧垂直标签的宽度
  2. 逐行输出:先写对应行的垂直标签,再写该行的数组元素,同时保证元素对齐

以下是修正后的代码,同时做了对齐优化,让输出更整齐:

public int[,] GetWeeklyAttendance()
{
    string[] timeLabels = {"1 PM", "3 PM", "5 PM", "7 PM"};
    string[] dayOfWeekLabels = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    int[,] weeklyAttendance =
    {
        {8, 10, 15, 20 },
        {11, 15, 17, 18 },
        {14, 12, 22, 20 },
        {9, 14, 17, 12 },
        {10, 12, 21, 22 },
        {12, 12, 7, 15 }
    };

    // 计算最长的垂直标签长度,用于对齐
    int maxLabelWidth = dayOfWeekLabels.Max(label => label.Length);
    
    // 输出顶部水平标签:先留空对应垂直标签的宽度,再输出时间标签
    Console.Write(new string(' ', maxLabelWidth) + " ");
    foreach (var time in timeLabels)
    {
        // 每个时间标签占6个字符宽度,保证对齐
        Console.Write($"{time,-6}");
    }
    Console.WriteLine();

    // 逐行输出:垂直标签 + 数组元素
    for (int i = 0; i < weeklyAttendance.GetLength(0); i++)
    {
        // 输出垂直标签,对齐到最长标签的宽度
        Console.Write($"{dayOfWeekLabels[i],-maxLabelWidth} ");
        for (int j = 0; j < weeklyAttendance.GetLength(1); j++)
        {
            // 每个数字占6个字符宽度,对齐输出
            Console.Write($"{weeklyAttendance[i,j],-6}");
        }
        Console.WriteLine();
    }

    return weeklyAttendance;
}

关键优化点:

  • 调整输出顺序,先处理顶部水平标签,用空格占位对应左侧垂直标签的位置
  • 使用$"{text,-width}"格式化语法,实现左对齐并固定宽度,保证所有内容整齐排列
  • 移除了原标签里的\n,避免提前换行打乱布局

运行后输出效果示例:

1 PM   3 PM   5 PM   7 PM   
Monday    8      10     15     20     
Tuesday   11     15     17     18     
Wednesday 14     12     22     20     
Thursday  9      14     17     12     
Friday    10     12     21     22     
Saturday  12     12     7      15     

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:55:15