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
相关产品推荐
相关产品推荐

