输出n层杨辉三角形c++代码
时间: 2023-12-25 13:49:12 浏览: 37
以下是输出n层杨辉三角形的C++代码:
```c++
#include <iostream>
using namespace std;
int main() {
int n;
cout << "请输入要输出的杨辉三角形的层数:";
cin >> n;
int a[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
a[i][j] = 1;
} else {
a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
}
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
这段代码先通过用户输入确定要输出的杨辉三角形的层数n,然后使用二维数组a存储杨辉三角形中每个数字的值。接着使用两个嵌套循环遍历二维数组a,并根据杨辉三角形的规律计算每个数字的值,最后输出杨辉三角形。
相关问题
杨辉三角形c++ 代码
下面是一个输出杨辉三角形的C++代码示例:
```
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int n, i = 0, j = 0;
cin >> n;
int a[n][n];
for (i = 0; i < n; i++) {
for (j = 0; j < i + 1; j++) {
if (j == 0 || j == i) a[i][j] = 1; else a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < i + 1; j++) {
cout << setiosflags(ios::left) << setw(8) << a[i][j];
}
cout << endl;
}
cout << endl;
return 0;
}
```
这个代码使用了二维数组来存储杨辉三角形中的数字,然后使用两个嵌套的循环来计算和输出杨辉三角形。在循环中,如果当前数字是第一列或最后一列,那么它的值为1,否则它的值为上一行的左上角和右上角数字之和。最后,使用setw()函数来设置输出的宽度,使输出的数字对齐。
c++输出等腰杨辉三角形
这是一个C语言实现等腰杨辉三角形输出的代码:
```c
#include <stdio.h>
int main() {
int rows, coef = 1, space, i, j;
printf("请输入杨辉三角的行数:");
scanf("%d", &rows);
for (i = 0; i < rows; i++) {
for (space = 1; space <= rows - i; space++) {
printf(" ");
}
for (j = 0; j <= i; j++) {
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
printf("%4d", coef);
}
printf("\n");
}
return 0;
}
```
这段代码会根据用户输入的行数,输出相应行数的等腰杨辉三角形。其中,每个数字用4个字符的宽度打印,并在数字之间留有空格。这样可以使输出的杨辉三角形更加整齐美观。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)