用printf输出树状图
时间: 2023-12-04 15:39:52 浏览: 32
树状图是一种常见的数据结构可视化方式,可以使用printf函数输出。下面是一个简单的例子:
```c++
#include <stdio.h>
void printTree(int depth) {
for (int i = 0; i < depth; i++) {
printf("| ");
}
printf("+-+\n");
if (depth < 3) {
printTree(depth + 1);
printTree(depth + 1);
}
}
int main() {
printTree(0);
return 0;
}
```
输出结果如下:
```
+-+
| +-+
| | +-+
| | | +-+
| | | +-+
| | +-+
| | | +-+
| | | +-+
| +-+
| | +-+
| | +-+
```
该例子使用递归方式打印了一个深度为3的树状图。printTree函数接受一个参数depth,表示当前节点的深度。在每个节点处,先打印出当前节点的父节点,然后再打印出当前节点的符号。如果当前节点深度小于3,则递归打印左右子树。
相关问题
c语言printf输出图形
可以使用printf函数输出一些简单的图形,例如矩形、三角形等。下面是一些示例代码:
输出矩形:
```
#include <stdio.h>
int main() {
int width = 10;
int height = 5;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
```
输出三角形:
```
#include <stdio.h>
int main() {
int height = 5;
for (int i = 0; i < height; i++) {
for (int j = 0; j <= i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
```
c 语言 printf 输出图形 题目
请编写一个程序,使用 printf 函数输出以下图形:
```
/\
/ \
/ \
/______\
| |
| |
| |
| |
|______|
```
提示:
- 可以使用多个 printf 函数语句,每个语句输出一行。
- 可以使用空格字符和转义字符 \ 。
答案:
```
printf(" /\\\n");
printf(" / \\\n");
printf(" / \\\n");
printf("/______\\\n");
printf("| |\n");
printf("| |\n");
printf("| |\n");
printf("| |\n");
printf("|______|\n");
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)