如何使用 C# 以三角形形式顯示數字?
要以三角形形式顯示數字,首先考慮一個二維陣列。
int[,] a = new int[5, 5];
對於一個三角形來說,按如下所示考慮空格 −
1 1 1 1 2 1 1 3 3 1
然後迴圈以在左右設定三角形的 1s,如下面的程式碼所示 −
示例
using System;
class Demo {
public static void Main() {
// two dimensional array
int[,] a = new int[5, 5];
for (int i = 0; i < 5; i++) {
for (int k = 7; k > i; k--) {
// prints spaces
Console.Write(" ");
}
// loop to print the triangle
for (int j = 0; j < i; j++) {
if (j == 0 || i == j) {
a[i, j] = 1;
} else {
a[i, j] = a[i - 1, j] + a[i - 1, j - 1];
}
Console.Write(a[i, j] + " ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}輸出
1 1 1 1 2 1 1 3 3 1
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP