首页 > 解决方案 > 我的嵌套循环打印的行比想要/预期的少

问题描述

我需要提示用户选择 h 并使用 h 打印出每行递增 1 的行数。所以我理解这部分并且我已经嵌套了我的循环但是当我选择 exmp: h=4 它打印3 行。我是编程的初学者,并且已经为此烦恼了几天:P

我希望你给我一些提示如何自己解决这个问题,而不仅仅是为了获得答案。谢谢你!

for (int i = 0; i < h; i++)
{
          for( int j = 0; j < i; j++)
          {
              printf("#");
          }
     printf("\n");
}
   }

标签: cloopsfor-loopnested-loops

解决方案


The outer loop iterates exactly h times.

However for the first iteration when i is equal to 0 the inner loop is skipped because the condition of the loop

for( int j = 0; j < i; j++)
                ^^^^^

evaluates to false.

It seems what you mean is the following

#include <stdio.h>

int main(void) 
{
    while ( 1 )
    {
        printf( "Enter the height of a pyramid (0 - exit): " );

        unsigned int h;

        if ( scanf( "%u", &h ) != 1 || h == 0 ) break;

        putchar( '\n' );

        for ( unsigned int i = 0; i < h; i++ )
        {
            for ( unsigned int j = 0; j < i + 1; j++)
            {
                printf( "#" );
            }
            putchar( '\n' );
        }

        putchar( '\n' );
    }

    return 0;
}

the program output might look like

Enter the height of a pyramid (0 - exit): 10

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

Enter the height of a pyramid (0 - exit): 0

推荐阅读