用c++写一个杨辉三角
时间: 2024-02-18 13:33:54 浏览: 53
以下是用C语言编写的杨辉三角程序:
```c
#include <stdio.h>
int main()
{
int rows, coef = 1;
printf("Enter the number of rows: ");
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;
}
```
运行程序后,输入要打印的行数,程序就会输出对应的杨辉三角。例如,输入5,程序输出如下:
```
Enter the number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
相关问题
用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;
}
```
这个程序可以根据用户输入的行数,输出相应行数的杨辉三角。
帮我用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;
}
```
当你运行程序时,它将提示您输入要打印的行数,然后按照杨辉三角的规则打印出相应数量的行。
阅读全文
相关推荐












