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

C语言水平排列等边三角形问题求助:仅第一个三角形符合要求

问题分析与解决方案

你的代码核心问题在于:每个三角形的左侧空格是从整个行的起始位置计算的(j<=5-i),这导致后续所有三角形都从行首重复添加大量空格,位置完全偏离,无法形成水平对齐的等边三角形。

正确的思路是让每个三角形在独立的固定宽度区块内居中——高度为3的等边三角形最大宽度是5,所以每个区块宽度设为5,保证每个三角形的每行内容都占满5个字符,这样多个三角形并排时自然对齐。

修正后的代码

#include <stdio.h>

int main(){
    int triangles, i, h, j;      
    printf("How many triangles do you want to print: ");    
    scanf("%d", &triangles);

    if (triangles > 4)
        printf("Up to 4 triangles only");   
    else{   
        // 遍历三角形的每一行(共3行)
        for (i = 1; i <= 3; i++){ 
            // 遍历要打印的三角形数量
            for (h = 1; h <= triangles; h++){   
                // 计算左侧空格:使星号在5字符宽度内居中
                int left_spaces = (5 - (2*i - 1)) / 2;
                for (j = 0; j < left_spaces; j++){ 
                    printf(" ");
                }
                // 打印当前行的星号
                for (j = 0; j < 2*i - 1; j++){ 
                    printf("*");
                }
                // 打印右侧空格,占满5字符宽度,确保对齐
                int right_spaces = 5 - left_spaces - (2*i - 1);
                for (j = 0; j < right_spaces; j++){ 
                    printf(" ");
                }
                // 三角形之间添加1个空格分隔(可按需调整数量)
                if (h != triangles) {
                    printf(" ");
                }
            }
            printf("\n");   
        }
    }
    return 0;
}

关键修正点

  1. 居中空格计算:通过(5 - (2*i -1))/2计算每行左侧需要的空格数,这是等边三角形居中的标准逻辑,确保星号在5字符区块内居中。
  2. 右侧补全空格:添加右侧空格让每个三角形的每行内容占满5个字符,避免后续三角形位置偏移。
  3. 间隔控制:在非最后一个三角形后添加分隔空格,让多个三角形之间边界清晰。

测试输出(输入3时)

*     *     * 
 ***   ***   ***
***** ***** *****

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:27:28