用c++编程输出杨辉三角前七行
时间: 2023-12-08 19:02:58 浏览: 84
下面是用C++语言编写的输出杨辉三角前七行的程序:
```c++
#include <iostream>
using namespace std;
int main() {
int n = 7;
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;
}
```
输出结果:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
```
相关问题
用c++编程实现输出杨辉三角形前 10 行
以下是使用C语言编写输出前10行杨辉三角形的程序:
```
#include <stdio.h>
int main() {
int rows = 10;
int coef = 1;
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++输出杨辉三角形的前n行。
好的,以下是使用C语言输出杨辉三角形前n行的代码:
```
#include <stdio.h>
int main() {
int n, coef = 1, i, j;
printf("Enter the number of rows: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
for (j = 1; j <= n - i; j++) {
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;
}
```
这段代码使用两个for循环来打印出每一行的数字,其中第一个循环负责输出每行前面的空格,第二个循环计算并输出杨辉三角中的数字。 您可以将输入的n更改为您想要的任何数字以输出任意数量的行。
相关推荐
![](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)