c - 我的嵌套循环打印的行比想要/预期的少
问题描述
我需要提示用户选择 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");
}
}
解决方案
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
推荐阅读
- typo3 - Typo3 后端 HTML 元素 - 格式值错误
- batch-file - 如何批量淡入淡出多个视频ffmpeg?
- python - python pandas将逗号分隔的值放入带有“title”的列中
- google-api - 验证 Google Drive 请求
- c# - 如何在c#中返回具有复杂结构的字符串数组
- c++ - 纯虚函数可以是可变函数模板吗?
- git - Git rebase 很多冲突
- python - 在 Snakemake 中使用 cutadapt 适配器文件输入
- html - 我们如何检查是否所有的 div 都显示为 none
- github - Github API 来管理对安全警报的访问?