怎么用c++写杨辉三角
时间: 2023-04-03 12:03:38 浏览: 65
可以使用以下代码来用 C 语言写杨辉三角:
#include <stdio.h>
int main() {
int rows, coef = 1;
printf("请输入行数:");
scanf("%d", &rows);
for(int i = 0; i < rows; i++) {
for(int space = 1; space <= rows - i; space++) {
printf(" ");
}
for(int 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;
}
相关问题
用队列写杨辉三角c++
好的,以下是用队列写杨辉三角的 C++ 代码:
```c++
#include <iostream>
#include <queue>
using namespace std;
void PascalTriangle(int n) {
queue<int> q;
q.push(1); // 第一行只有一个数 1
for (int i = 1; i <= n; i++) {
int pre = 0; // 上一行的数
for (int j = 0; j < i; j++) {
int cur = q.front(); // 当前数
q.pop();
cout << cur << " "; // 输出当前数
q.push(pre + cur); // 计算下一行的数并加入队列
pre = cur; // 更新上一行的数
}
q.push(1); // 每行最后一个数也是 1
cout << endl;
}
}
int main() {
int n;
cout << "请输入要输出的行数:";
cin >> n;
PascalTriangle(n);
return 0;
}
```
运行程序后,根据提示输入要输出的行数,即可输出相应行数的杨辉三角。
如何用c++打印杨辉三角
要用C++打印杨辉三角,可以使用二维数组存储杨辉三角的每个数,然后按照规律打印出来。以下是一种实现方法:
1. 定义一个二维数组a[n][n],其中n为杨辉三角的层数。
2. 对于每一行i,a[i]和a[i][i]都为1,对于其他位置a[i][j],有a[i][j] = a[i-1][j-1] + a[i-1][j]。
3. 打印杨辉三角时,对于每一行i,先打印n-1-i个空格,然后打印a[i]到a[i][i]的数,每个数之间用空格隔开。
以下是代码实现:
```
#include <iostream>
using namespace std;
int main() {
const int n = 5; // 杨辉三角的层数
int a[n][n]; // 存储杨辉三角的每个数
// 计算杨辉三角
for (int i = 0; i < n; i++) {
a[i][0] = 1;
a[i][i] = 1;
for (int j = 1; j < i; j++) {
a[i][j] = a[i-1][j-1] + a[i-1][j];
}
}
// 打印杨辉三角
for (int i = 0; i < n; i++) {
for (int j = 0; j < n-1-i; j++) {
cout << " "; // 打印每行开始的空格
}
for (int j = 0; j <= i; j++) {
cout << a[i][j] << " "; // 打印每行的数
}
cout << endl;
}
return 0;
}
```