You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++实现树形结构打印并在同一子程序返回平均值的问题求解

问题修复方案

1. 树形结构打印异常修复

你之前的左侧填充逻辑错误,setw() 是用于设置下一次输出操作的宽度,嵌套循环+动态调整setw的写法会导致输出长度完全失控。正确逻辑如下:

  • 对于高度为tree的树,第i层(i从0到tree)的左侧需要填充tree - i个空格,保证整棵树居中对齐
  • 空格后输出i个短横,再输出|,再输出i个短横即可
  • 最后树干的|也需要前置tree个空格,和树顶对齐

2. 函数返回平均值逻辑修复

  • 把print_tree的返回值类型从void改成double,函数结束时返回计算好的平均值即可
  • 移除原来在print_tree内部直接打印平均值的逻辑,平均值输出放到main函数里,和提示语顺序匹配
  • 删除冗余的calculate_median函数,直接在print_tree中完成平均值计算返回即可

修改后完整代码

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

double print_tree() {
    int sum = 0;
    int tree = 0;
    int counter = 0;
    
    cout << "Type integers: ";
    while (cin >> tree) {
        counter++;
        sum += tree;

        for (int i = 0; i <= tree; ++i) {    
            // 先填充左侧空格,保证树居中
            cout << string(tree - i, ' ');
            // 左侧短横
            cout << string(i, '-');
            // 中间竖线
            cout << '|';
            // 右侧短横
            cout << string(i, '-') << '\n';
        }
        // 树干对齐
        cout << string(tree, ' ') << '|' << endl;
    }
    // 返回平均值
    return static_cast<double>(sum) / static_cast<double>(counter);
}
  
int main() {
    double avg = print_tree();
    cout << "The average value was: " << fixed << setprecision(1) << avg << endl;
    return 0;
}

运行效果验证

输入2 1 4后输出完全匹配预期:

Type integers: 2 1 4

  |
 -|-
--|--
  |
 |
-|-
 |
    |
   -|-
  --|--
 ---|---
----|----
    |
The average value was: 2.3

内容的提问来源于stack exchange,提问作者leun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:45:01