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

C#中如何使用二维数组正确打印反向阶梯图案

问题描述

在C#中尝试使用二维数组打印反向阶梯图案时,多次调整循环逻辑后,程序要么无任何输出,要么打印出倒三角形图案,无法得到预期效果。预期反向阶梯样式如下:
预期反向阶梯图案

原有问题代码
static void Main(string[] args)
{
    char[,] shape = new char[5, 5];

    
    //Makes Stairs
    //for (int i = 0; i < shape.GetLength(0); i++)
    //{
    //    for (int j = 0; j <= i; j++)
    //    {
    //        shape[i, j] = '*';
    //    }
    //}
    //--------------------------------------------
    
    //*****Makes Reverse Stair: Right now only prints upside down triangle
    for (int i = 0; i < shape.GetLength(0); i++)
    {
        for (int j = 0; j < shape.GetLength(1); j++)
        {
            if (j >= i)
            {
                shape[i, j] = '*';
            }
        }
    }
}
问题原因
  • 数组中非*的位置没有显式赋值空格,char类型默认值是\0空字符,打印时不会显示,是导致无输出的核心原因
  • 原有判断逻辑j >= i会生成左对齐的倒三角形,和预期的右对齐反向阶梯逻辑不符
  • 代码仅完成了数组赋值,没有编写遍历数组打印内容的逻辑
正确实现代码

核心逻辑:逐行填充时,从每行右侧开始放置*,第i行(从0开始计数)放置i+1个*,其余位置填充空格,填充完成后逐字符遍历打印,每行结束后换行。

static void Main(string[] args)
{
    char[,] shape = new char[5, 5];
    int rowCount = shape.GetLength(0);
    int colCount = shape.GetLength(1);

    // 填充二维数组
    for (int i = 0; i < rowCount; i++)
    {
        for (int j = 0; j < colCount; j++)
        {
            // 从每行右侧开始,填充对应数量的*,其余位置填空格
            if (j >= colCount - 1 - i)
            {
                shape[i, j] = '*';
            }
            else
            {
                shape[i, j] = ' ';
            }
        }
    }

    // 打印图案
    for (int i = 0; i < rowCount; i++)
    {
        for (int j = 0; j < colCount; j++)
        {
            Console.Write(shape[i, j]);
        }
        Console.WriteLine();
    }
}

运行后输出效果和预期一致:

*
   **
  ***
 ****
*****

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 02:36:27