c语言编写函数void printTriangle(int n), 输出如下 图的n行的三角形 * * * * * * * * * * *****
时间: 2023-07-05 13:25:12 浏览: 72
好的,下面是实现该函数的代码:
```c
void printTriangle(int n) {
int i, j;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n - i; j++) {
printf(" ");
}
for (j = 1; j <= i * 2 - 1; j++) {
printf("* ");
}
printf("\n");
}
}
```
该函数会输出如下图形的n行三角形:
```
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
```
调用该函数时,将n传入即可打印出相应行数的三角形。
相关问题
C语言用递归函数输出由n行*组成的三角形
使用递归函数输出由n行*组成的三角形的C语言代码如下:
```c
#include <stdio.h>
void printTriangle(int n) {
if (n == 0) { // 递归出口,当n为0时结束递归
return;
}
printTriangle(n - 1); // 递归调用,先打印前n-1行的三角形
for (int i = 0; i < n; i++) {
printf("* "); // 每行打印n个*
}
printf("\n"); // 换行
}
int main() {
int n = 6; // 设置三角形行数
printTriangle(n);
return 0;
}
```
该代码首先通过递归调用`printTriangle(n - 1)`打印前n-1行的三角形,然后在第n行打印n个*。
编写一个函数,当输入整数n后,输出高度为n的等边三角形。当n=4时的等边三角形如下: * *** ***** *******
以下是C语言实现高度为n的等边三角形的代码:
```c
#include <stdio.h>
void printTriangle(int n) {
int i, j, k;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n - i; j++) {
printf(" ");
}
for (k = 1; k <= 2 * i - 1; k++) {
printf("*");
}
printf("\n");
}
}
int main() {
int n;
printf("请输入一个整数:");
scanf("%d", &n);
printTriangle(n);
return 0;
}
```
当输入4时,输出的等边三角形如下:
```
*
***
*****
*******
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)