杨辉三角的c++代码,并给出详细注释
时间: 2023-05-24 09:06:09 浏览: 72
#include <stdio.h>
int main() {
int row, col, coef = 1;
printf("Enter the number of rows: ");
scanf("%d", &row);
// loop through each row
for(int i = 0; i < row; i++) {
// print the spaces
for(int space = 1; space < row - i; space++) {
printf(" ");
}
// loop through each column
for(int j = 0; j <= i; j++) {
// print the coefficient
if (j == 0 || i == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
printf("%4d", coef);
}
printf("\n");
}
return 0;
}
/*
Output:
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
*/
// Explanation:
// The outer loop is for each row of the triangle
// The inner loop is for each column of the triangle
// In the inner loop, we calculate the coefficient using the formula for binomial coefficients
// Then we print out the coefficient in the correct format, with spaces to align the triangle
// Finally, we print a newline character to move onto the next row of the triangle.
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)