在 C 中看起来像三角形的输出 [英] Output that looks like a triangle in C
问题描述
我写了这个程序,
include <stdio.h>
int main(){
int size = 5;
int row;
int col;
for (col=0; col<size; col++){
for (row=0; row<col;row++){
printf(" ");
}
for (row=0; row <(size-col) ; row++){
printf("*");
if(col<=size){
printf("*");
}
}
printf("
");
}
return 0;
}
它应该是一个三角形
*********
*******
*****
***
*
但是每一行都有一个额外的 * .有什么问题?
But instead there is one extra * on every line. What is the problem?
非常感谢!
推荐答案
Mystical 有一个解决方案,可以解决您在一次迭代中打印两个星号的方式.在您的示例中使用标识符 row
和 col
也会使事情比仅使用 i
和 j
更令人困惑,尤其是因为外循环实际上是您的当前行.
Mystical has a solution to the way you're printing two asterisks an iteration. Using the identifiers row
and col
in your example also makes things more confusing than just i
and j
, especially since the outer loop is actually your current row.
你的烂摊子的另一种选择是(我希望这不是家庭作业,因为它没有被标记):
An alternative to your mess is (I'm hoping this isn't homework since it's not tagged as such):
int main(void)
{
int size = 5;
int i, j;
for (i = size; i > 0; i--) {
for (j = i; j < size; j++)
putchar(' ');
for (j = 0; j < i*2 - 1; j++)
putchar('*');
putchar('
');
}
return 0;
}
您也可以将 i*2 - 1
放在一个变量中,这样就不会在循环的每次迭代中计算它(除非编译器发现您没有修改 i代码>).
You could also put i*2 - 1
in a variable so that it's not calculated at each iteration of the loop (unless the compiler sees that you're not modifying i
).
这篇关于在 C 中看起来像三角形的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!