用c++数组写一个杨辉三角
时间: 2023-04-10 17:03:44 浏览: 80
以下是用 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++二维数组求杨辉三角的代码:
```cpp
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "请输入杨辉三角的行数:";
cin >> n;
int a[n][n];
// 初始化第一行和对角线上的元素为1
for (int i = 0; i < n; i++) {
a[i][0] = 1;
a[i][i] = 1;
}
// 计算其余元素
for (int i = 2; i < n; i++) {
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 <= i; j++) {
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
运行结果:
```
请输入杨辉三角的行数:6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```
用c++语法写出二维数组杨辉三角形
好的,以下是用 C 语法写的杨辉三角形二维数组:
```
#include<stdio.h>
int main()
{
int rows, coef = 1;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(int i=0;i<rows;i++)
{
for(int j=0;j<=i;j++)
{
if (j==0 || i==0)
coef = 1;
else
coef = coef*(i-j+1)/j; // Using Pascal's Formula
printf("%d ",coef);
}
printf("\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)