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

如何用C语言实现镜像对称的节日树形文字排版效果

C语言实现镜像对称节日树的修改方案

你的代码核心问题是所有行固定前置了4个空格,没有根据每行字符串长度动态调整缩进量,导致|无法对齐,最终呈现不出对称树效果。可以参考以下逻辑修改:

  • 先读取所有输入的字符串,统计出最长的字符串长度
  • 每行打印时,先输出(最长字符串长度 - 当前行字符串长度)个前置空格,再输出当前字符串|当前字符串格式的内容
  • 废弃不安全的gets()函数,改用fgets()避免缓冲区溢出

修改后的可运行代码如下:

#include <stdio.h>
#include <string.h>

#define LINE_NUM 5  // 对应示例的5行文字,可按需调整
#define MAX_LEN 50

int main() {
    char strs[LINE_NUM][MAX_LEN];
    int max_len = 0;
    
    // 读取所有行,同时统计最长字符串长度
    for (int i = 0; i < LINE_NUM; i++) {
        fgets(strs[i], MAX_LEN, stdin);
        // 去掉末尾的换行符
        strs[i][strcspn(strs[i], "\n")] = '\0';
        int cur_len = strlen(strs[i]);
        if (cur_len > max_len) {
            max_len = cur_len;
        }
    }
    
    // 按镜像格式打印
    for (int i = 0; i < LINE_NUM; i++) {
        int cur_len = strlen(strs[i]);
        // 输出前置空格
        for (int j = 0; j < max_len - cur_len; j++) {
            printf(" ");
        }
        printf("%s|%s\n", strs[i], strs[i]);
    }
    return 0;
}

运行时按顺序输入Jojo、is、the、Best、Intheworld,就能得到你需要的对称效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:45:05