用c++这一个杨辉三角
时间: 2023-04-03 08:00:43 浏览: 64
我可以回答这个问题。杨辉三角是一个数学图形,可以用 C 语言编写程序来生成。以下是一个简单的示例代码:
#include <stdio.h>
int main() {
int rows, coef = 1, space, i, j;
printf("请输入行数:");
scanf("%d", &rows);
for (i = ; i < rows; i++) {
for (space = 1; space <= rows - i; space++)
printf(" ");
for (j = ; j <= i; j++) {
if (j == || i == )
coef = 1;
else
coef = coef * (i - j + 1) / j;
printf("%4d", coef);
}
printf("\n");
}
return ;
}
这个程序可以让用户输入行数,然后生成相应行数的杨辉三角。
相关问题
用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语言编写的杨辉三角程序:
```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
```