用c语言编写杨辉三角
时间: 2023-10-13 07:06:16 浏览: 126
以下是用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)。