杨辉三角形c++ 代码
时间: 2023-12-10 09:33:01 浏览: 42
下面是一个输出杨辉三角形的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()函数来设置输出的宽度,使输出的数字对齐。
相关问题
输出n层杨辉三角形c++代码
以下是输出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++队列实现杨辉三角形的代码:
```c++
#include <iostream>
#include <queue>
using namespace std;
void printPascal(int n) {
queue<int> q;
q.push(1); // 第一行只有一个1
for (int i = 1; i <= n; i++) {
int prev = 0; // 记录上一行的数字
for (int j = 0; j < i; j++) {
int curr = q.front();
q.pop();
cout << curr << " ";
int sum = prev + curr; // 计算当前数字
prev = curr;
q.push(sum); // 将当前数字加入队列
}
q.push(1); // 每行最后一个数字为1
cout << endl;
}
}
int main() {
int n = 5;
printPascal(n);
return 0;
}
```
相关推荐
![](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)