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

while与for循环未生成预期金字塔结构,请求技术排查

问题描述

我想要生成如下的金字塔结构:

#
##
###
####
#####
######
#######
########

但我的代码实际只输出一行。我已经尝试修改while和for循环的条件,还是没解决问题,求帮忙!我的代码如下:

#include <stdio.h>
#include <cs50.h>

int main(void)
{

    int n = get_int("Add the height of the pyramid: ");
    int j = 0;
    for(int i = 0; i < n ; i++) {
        while (j <= i) {
            printf("#");
            j = j + 1;
        }
        printf("\n");

}

问题原因

核心问题出在变量j的初始化位置:你把j定义在for循环外部,第一次for循环迭代完成后,j的值会累计到等于n(比如输入高度为8时,j最终会变成8)。后续的for循环迭代中,j <= i的条件永远不成立,导致while循环不再执行,所以只会输出第一行内容。

解决方案

有三种可行的修改方式:

方式1:将j的定义移到for循环内部

每次for循环迭代时都重置j的初始值:

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    int n = get_int("Add the height of the pyramid: ");
    for(int i = 0; i < n ; i++) {
        int j = 0; // 每次循环重置j为0
        while (j <= i) {
            printf("#");
            j = j + 1;
        }
        printf("\n");
    }
}

方式2:在for循环末尾重置j

保留j的外部定义,每次循环结束后手动重置:

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    int n = get_int("Add the height of the pyramid: ");
    int j = 0;
    for(int i = 0; i < n ; i++) {
        while (j <= i) {
            printf("#");
            j = j + 1;
        }
        printf("\n");
        j = 0; // 循环结束后重置j
    }
}

方式3:改用嵌套for循环(更简洁)

直接用两层for循环实现,无需额外处理变量重置:

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    int n = get_int("Add the height of the pyramid: ");
    for(int i = 0; i < n ; i++) {
        for(int j = 0; j <= i; j++) {
            printf("#");
        }
        printf("\n");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:45:54