创建一个三角形 [英] Create a triangle
本文介绍了创建一个三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要创建这样一个三角形
I need to create a triangle like this
*
**
***
****
*****
我已经做到了这一点。但我的三角形不会是这样的:
I have done this. But my triangle does not look like this:
#include <stdio.h>
int main()
{
int k, l;
for(k=1; k<=5; k++)
{
for(l=k; l<=5; l++)
printf(" ");
for(l=0; l<=k-1; l++) printf("*");
printf("\n");
}
return 0;
}
你会告诉我,我的错误是什么?
will you tell me where my mistake is?
推荐答案
您不需要3循环 - 这是不必要的:
You do not need 3 loops - that is unnecessary:
int k, l;
for(k=1; k<=5; k++) // outer loop
{
for(l=0; l<k; l++) // inner loop
printf("*");
printf("\n");
}
我们的想法是在内环简单的保持印刷明星只要→
小于 K
。因此,作为行数量的增加也是如此的星数(按 K
跟踪)。您的固定code:
The idea is simple keep printing stars in inner loop as long as l
is less than k
. So as the row-number increases (tracked by k
) so does the number of stars. Your fixed code:
for(k=1; k<=5; k++)
{
for(l=0; l<=k-1; l++) printf("*");
printf("\n");
}
这篇关于创建一个三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文