僅使用**一個** 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));
}
}
}
| i | distFromMid | starCount | 輸出 |
|---|---|---|---|
| 0 | 4 | 1 | * |
| 1 | 3 | 3 | *** |
| 2 | 2 | 5 | ***** |
| 3 | 1 | 7 | ******* |
| 4 | 0 | 9 | ********* |
| 5 | 1 | 7 | ******* |
| 6 | 2 | 5 | ***** |
| 7 | 3 | 3 | *** |
| 8 | 4 | 1 | * |
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 避免巢狀迴圈