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

请求修改C#代码实现三角正弦波格式字符串输出

实现三角正弦波格式字符串输出

我需要写一个C#函数,输出**三角正弦波(Triangle Sine-Wave)**格式的字符串——也就是字符在每行连续成段排列,形成类似三角的波形;但目前的代码只能生成普通的Z字形波形。

现有代码如下:

public static void printWave(string str)
{
    int height = 3;
    int len = str.Length;

    char[,] matrixArray = new char[height, len];
    char[] charArray = str.ToCharArray();
    
    int row = 0;
    bool down = true;

    for (int i = 0; i < len; i++)
    {
        matrixArray[row, i] = charArray[i];

        if (row == height - 1)
            down = false;
        else if (row == 0)
            down = true;

        row = down ? row + 1 : row - 1;
    }

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < len; j++)
        {
            Console.Write(matrixArray[i, j] + " ");
        }
        Console.Write("\n");
    }
}

修改后的实现代码

原代码的问题是逐个字符切换行,而三角正弦波需要每行连续填充一段字符。以高度3为例,波形的周期是2*(height-1),每个周期内:顶部行填1个字符、中间行填2个、底部行填1个,循环往复。

修改后的代码如下:

public static void printTriangleSineWave(string str)
{
    int height = 3;
    int strLen = str.Length;
    char[,] waveMatrix = new char[height, strLen];
    char[] charArr = str.ToCharArray();
    
    int charIndex = 0;
    int cycleLength = 2 * (height - 1); // 三角波形的完整周期长度

    for (int col = 0; col < strLen && charIndex < strLen; col++)
    {
        int cyclePos = col % cycleLength;
        int fillRowCount;

        // 确定当前列要填充的行数:上升阶段递增,下降阶段递减
        if (cyclePos < height)
        {
            fillRowCount = cyclePos + 1;
        }
        else
        {
            fillRowCount = cycleLength - cyclePos + 1;
        }

        // 填充对应行的当前列
        for (int row = 0; row < fillRowCount && charIndex < strLen; row++)
        {
            waveMatrix[row, col] = charArr[charIndex++];
        }
    }

    // 打印波形,空字符用空格替代保证对齐
    for (int row = 0; row < height; row++)
    {
        for (int col = 0; col < strLen; col++)
        {
            Console.Write(waveMatrix[row, col] == '\0' ? "  " : waveMatrix[row, col] + " ");
        }
        Console.WriteLine();
    }
}

关键改动说明

  1. 周期逻辑:用2*(height-1)定义完整波形周期,对应从顶部到底部再回到顶部的过程
  2. 填充规则:
    • 周期前半段(上升):每列填充的行数从1逐步增加到height
    • 周期后半段(下降):每列填充的行数从height-1逐步减少到1
  3. 对齐处理:打印时把未填充的空字符替换成两个空格,让波形对齐更整齐

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:45:33