分别采用双重循环和二维字符数组的函数实现如下的三角形星号图,程序可以改变行数、星号并统计字符数。 正立三角形 * *** ***** ******* *********
时间: 2024-06-15 18:06:46 浏览: 15
要实现正立三角形星号图,可以使用双重循环或二维字符数组的方式来实现。下面是使用双重循环的实现方法:
```c
#include <stdio.h>
void printTriangle(int rows, char symbol) {
int i, j, k;
int numChars = 0;
for (i = 1; i <= rows; i++) {
for (j = 1; j <= rows - i; j++) {
printf(" "); // 打印空格
}
for (k = 1; k <= 2 * i - 1; k++) {
printf("%c ", symbol); // 打印星号
numChars++;
}
printf("\n");
}
printf("字符数:%d\n", numChars);
}
int main() {
int rows;
char symbol;
printf("请输入行数:");
scanf("%d", &rows);
printf("请输入星号字符:");
scanf(" %c", &symbol);
printTriangle(rows, symbol);
return 0;
}
```
使用二维字符数组的方式实现如下:
```c
#include <stdio.h>
void printTriangle(int rows, char symbol) {
int i, j;
int numChars = 0;
char triangle[rows][2 * rows - 1];
// 初始化二维字符数组
for (i = 0; i < rows; i++) {
for (j = 0; j < 2 * rows - 1; j++) {
triangle[i][j] = ' ';
}
}
// 填充星号
for (i = 0; i < rows; i++) {
for (j = rows - i - 1; j <= rows + i - 1; j++) {
triangle[i][j] = symbol;
numChars++;
}
}
// 打印二维字符数组
for (i = 0; i < rows; i++) {
for (j = 0; j < 2 * rows - 1; j++) {
printf("%c ", triangle[i][j]);
}
printf("\n");
}
printf("字符数:%d\n", numChars);
}
int main() {
int rows;
char symbol;
printf("请输入行数:");
scanf("%d", &rows);
printf("请输入星号字符:");
scanf(" %c", &symbol);
printTriangle(rows, symbol);
return 0;
}
```
以上两种方式都可以实现正立三角形星号图,并统计字符数。你可以根据需要选择其中一种方式来使用。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)