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

C#将Main中星形金字塔逻辑迁移到TowerBuilder方法返回字符串数组

问题原因

你当前代码的核心问题是将循环变量同时用作数组下标和星号数量计数,导致两个需求冲突。

解决思路

将两个计数逻辑拆分:

  • 数组下标保持从0到nFloors-1连续遍历,确保每个数组元素都被正确赋值
  • 第i层(下标从0开始)对应的星号数量通过公式2*i + 1计算,刚好满足1、3、5...的奇数序列要求

正确实现代码

public static string[] TowerBuilder(int nFloors)
{
    int totalLineLength = nFloors * 2 - 1;
    string[] towerArr = new string[nFloors];
    
    for (int i = 0; i < nFloors; i++)
    {
        int starCount = 2 * i + 1;
        int paddingSpaceCount = (totalLineLength - starCount) / 2;
        towerArr[i] = new string(' ', paddingSpaceCount) + new string('*', starCount) + new string(' ', paddingSpaceCount);
    }
    
    return towerArr;
}

验证说明

传入nFloors=6时,返回的数组元素和你给出的控制台输出完全一致,每一层的长度都为nFloors*2-1,符合金字塔格式要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:45:03