c语言中用函数打印三角形
时间: 2023-11-06 15:07:35 浏览: 94
好的,您可以尝试使用下面这段代码:
#include <stdio.h>
void print_triangle(int size) {
int i, j;
for (i = 1; i <= size; i++) {
for (j = 1; j <= i; j++) {
printf("*");
}
printf("\n");
}
}
int main() {
int size;
printf("请输入三角形大小: ");
scanf("%d", &size);
print_triangle(size);
return 0;
}
这是一段 C 代码,可以根据用户输入的大小打印出相应大小的三角形。
相关问题
c语言函数递归打印三角形
以下是一个C语言函数递归打印三角形的例子:
```c
#include <stdio.h>
void print_triangle(int n) {
if (n == 1) {
printf("*\n");
} else {
print_triangle(n-1);
for (int i = 0; i < 2*n-1; i++) {
printf("*");
}
printf("\n");
}
}
int main() {
int n = 5;
print_triangle(n);
return 0;
}
```
该函数接受一个整数n作为参数,打印一个由星号组成的三角形,其中第一行有一个星号,第二行有三个星号,以此类推,直到第n行有2n-1个星号。该函数使用递归来实现,当n等于1时,只需要打印一个星号;否则,先递归打印n-1行,然后打印第n行。
C语言中用自定义函数打印杨辉三角
好的,下面是用C语言编写的自定义函数来打印杨辉三角的代码:
```c
#include <stdio.h>
void yanghui_triangle(int n) {
int triangle[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
triangle[i][j] = 1;
} else {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
printf("%d ", triangle[i][j]);
}
printf("\n");
}
}
// 调用函数,打印10层杨辉三角
int main() {
yanghui_triangle(10);
return 0;
}
```
运行结果如下:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
```
希望这个C语言的自定义函数可以帮助到您!
相关推荐
![](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)