萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 單一 for 迴圈輸出對稱三角形:String 建構子技巧

題目

僅使用**一個** for 迴圈,輸出對稱三角形:

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

關鍵技巧:new string(char, count)

string 建構子可重複字元:new string('*', 5) → "*****"。

完整程式碼


using System;

class Program {
    static void Main() {
        Render(9);  // 9 行 (奇數行對稱)
        Console.ReadLine();
    }

    static void Render(int rows) {
        if (rows <= 0 || rows % 2 == 0) return;  // 僅處理奇數行
        
        int mid = rows / 2;  // 中央行索引 (0-based)
        
        for (int i = 0; i < rows; i++) {
            // 計算當前行距離中間行的距離
            int distFromMid = Math.Abs(i - mid);
            // 星號數 = 總行數 - 2 * 距離
            int starCount = rows - 2 * distFromMid;
            
            Console.WriteLine(new string('*', starCount));
        }
    }
}

邏輯解析

idistFromMidstarCount輸出
041*
133***
225*****
317*******
409*********
517*******
625*****
733***
841*

延伸:偶數行、字元參數化


static void RenderFlexible(int rows, char ch = '*') {
    for (int i = 0; i < rows; i++) {
        int dist = Math.Abs(i - (rows - 1) / 2.0);  // 浮點中點
        int count = (int)(rows - 2 * dist);
        if (count > 0) Console.WriteLine(new string(ch, count));
    }
}

面試加分點

  • 說明 Math.Abs 對稱性
  • 指出 new string 避免巢狀迴圈
  • 討論偶數行處理、字元參數化、效能 (O(n) vs O(n²))
copyright © 萬盛學電腦網 all rights reserved