巴斯三角形怎么用编程编

时间:2025-01-29 03:25:29 网络游戏

1. 使用二维数组构建

```c

include

void printPascal(int n) {

int arr[n][n];

for (int i = 0; i < n; i++) {

for (int j = 0; j <= i; j++) {

if (j == 0 || j == i) {

arr[i][j] = 1;

} else {

arr[i][j] = arr[i-1][j-1] + arr[i-1][j];

}

}

}

for (int i = 0; i < n; i++) {

for (int j = 0; j <= i; j++) {

printf("%d ", arr[i][j]);

}

printf("\n");

}

}

int main() {

int n;

printf("Enter the number of rows for Pascal's Triangle: ");

scanf("%d", &n);

printPascal(n);

return 0;

}

```

2. 使用递推公式计算

```c++

include

include

long combi(int n, int r) {

int i;

long p = 1;

for (i = 1; i <= r; i++) {

p = p * (n - i + 1) / i;

}

return p;

}

void bskTriangle(int n) {

for (int n = 0; n <= 13; n++) {

for (int r = 0; r <= n; r++) {

int k;

if (r == 0) {

for (k = 0; k <= (13 - n); k++) {

std::cout << " "; // 每行第一个元素的位置

}

} else {

std::cout << " "; // 每个数之间空行

}

std::cout << std::setw(3) << combi(n, r) << " ";

}

std::cout << std::endl;

}

}

int main() {

bskTriangle(13);

return 0;

}

```

3. Python实现

```python

def barska(n):

res =

for i in range(n):

print(' ' * (n - i - 1), end='')

res.insert(0, 0)

for j in range(len(res) - 2):

res[j] += res[j + 1]

print(' %3d ' % res[j], end='')

res[len(res) - 2] = 1

print(' %3d ' % res[len(res) - 2], end='')

print()

def main():

n = int(input("Enter the number of rows for Pascal's Triangle: "))

barska(n)

if __name__ == "__main__":

main()

```

这些代码示例分别使用C语言、C++和Python实现了巴斯卡三角形的打印。你可以根据自己的需求和编程环境选择合适的实现方式。