c语言编写杨辉三角的小程序。
时间: 2023-04-06 08:03:23 浏览: 103
我可以回答这个问题。以下是一个简单的C语言程序,用于打印杨辉三角形:
#include <stdio.h>
int main() {
int rows, coef = 1, space, i, j;
printf("Enter the number of rows: ");
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;
}
相关问题
用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;
}
```
运行结果为:
```
Enter the number of rows: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```
在上面的代码中,我们首先要求用户输入杨辉三角的行数,然后使用嵌套的for循环来打印杨辉三角。在外层循环中,我们使用变量i来表示当前行数,从0到rows-1进行迭代。在内层循环中,我们使用变量j来表示当前列数,从0到i进行迭代。在每一行中,我们首先打印一些空格来进行对齐,然后计算组合数并打印出来。组合数的计算使用了递推公式C(i,j)=C(i-1,j-1)+C(i-1,j)。
c语言数组杨辉三角编程序
以下是用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;
}
```