You need to enable JavaScript to run this app. C#控制台打印圣诞树时树干无法居中问题求解
优惠活动
大模型
产品
解决方案
定价
更多

C#控制台打印圣诞树时树干无法居中问题求解

C#控制台圣诞树树干居中修复方案

问题根因

绘制完树冠后直接复用当前的spaces变量作为树干的缩进值,没有考虑树冠底部宽度和树干宽度的差值:

  • 树冠最后一行的星号区域总宽度为 widthOfTree * 2(每个*后带1个空格)
  • 树干的总宽度为 (widthOfTree / 3) * 2(每个|后带1个空格)
  • 缺失了「树冠宽度与树干宽度差值的一半」的前置空格,导致树干整体偏左

修复后完整代码

static void Main(string[] args)
{
    // 获取当前控制台窗口宽度
    int origWidth = Console.WindowWidth;

    int spaces = origWidth / 2;
    int widthOfTree = 1;

    Console.WriteLine("请输入想要生成的圣诞树高度");
    int treeHeightUserInput = 0;
    while (!int.TryParse(Console.ReadLine(), out treeHeightUserInput))
    {
        Console.WriteLine("请输入有效的数字!");               
    }

    // 绘制树冠
    for (int i = 0; i < treeHeightUserInput; i++)
    {
        // 输出前置空格
        for (int j = 0; j < spaces; j++)
        {
            Console.Write(" ");
        }
        // 输出星号
        for (int j = 0; j < widthOfTree; j++)
        {
            Console.Write("* ");
        }
        Console.WriteLine();
        widthOfTree++;
        spaces--;
    }

    // 绘制树干
    int trunkWidth = widthOfTree / 3;
    // 计算树干居中需要的缩进量
    int trunkIndent = spaces + (widthOfTree - trunkWidth) / 2;
    for (int i = 0; i < treeHeightUserInput / 3; i++)
    {
        for (int j = 0; j < trunkIndent; j++)
        {
            Console.Write(" ");
        }
        for (int j = 0; j < trunkWidth; j++)
        {
            Console.Write("| ");
        }
        Console.WriteLine();
    }
}

核心调整说明

  • 绘制树干前先单独计算树干宽度trunkWidth,避免重复计算
  • 新增树干缩进量trunkIndent,在原有spaces基础上补充了居中需要的偏移空格,确保树干正对树冠中轴线

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 13:45:03