只需参加一门在线课程,尝试分配诸如倒三角形的任务。我可以在python中做到这一点,但是由于C中的某种原因,它对我不起作用,特别是for循环的一部分,应该减小k值。在其他空白项目中也尝试过此方法,只是为了验证问题,但到目前为止,它对我来说不起作用。增加(j循环)有效,由于某种原因减少(k循环)无效(对于所有语法选项:k = k-1; k-= 1; k--)。
不知道问题出在哪里。
int main(void){
int height, i, j, k;
bool check = false;
while (check == false)
{
height = get_int("Height: ");
if (height >= 1 && height <= 8)
{
for (i = 0; i < height; i++)
{
for (k = height -2; k >=0; k--)
{
printf(".");
}
for (j = 0; j <= i; j++)
{
printf("#");
}
printf("\n");
}
check = true;
}
}}
对于高度5,这是目标输出
....#
...##
..###
.####
#####
这是实际输出
....#
....##
....###
....#####
....######
答案 0 :(得分:0)
在第二个循环中,k
必须是>= i
,而不是>= 0
。我将get_int
替换为5
。
int main(void){
int height, i, j, k;
bool check = false;
while (check == false)
{
height = 5;
if (height >= 1 && height <= 8)
{
for (i = 0; i < height; i++)
{
for (k = height -2; k >= i; k--)
{
printf(".");
}
for (j = 0; j <= i; j++)
{
printf("#");
}
printf("\n");
}
check = true;
}
}}
输出:
....#
...##
..###
.####
#####
答案 1 :(得分:0)
您的变量height
在构建输出时不会改变。您总是从k = 3开始。您如何期望输出的.
数量发生变化?
在打印出i
时尝试使用变量.
。
答案 2 :(得分:0)
只需将for循环语句更改为
for (k = height - 1; k >=i; k--)
k索引必须从'height'-1开始到i变量结束。
因此,对于高度= 5,第一个内部for循环将执行5次,当i增加1时,内部for循环将执行负1次,依此类推。
答案 3 :(得分:0)
k的值正在减小,但是k的for循环正在运行的范围与输入变量的高度保持不变。结果,它总是打印4(高2 + 1)点。要澄清更多信息,请参见以下步骤:
input->height 5
i = 0, printing four dots for k = 3,2,1,0. printing one '#' for j=0
i = 1, printing four dots for k = 3,2,1,0. printing two '#' for j=0,1
i = 2, printing four dots for k = 3,2,1,0. printing three '#' for j=0,1,2
i = 3, printing four dots for k = 3,2,1,0. printing four '#' for j=0,1,2,3
i = 4, printing four dots for k = 3,2,1,0. printing five '#' for j=0,1,2,3,4
for (k = height -i-2; k >=0; k--) //to decrease starting value of k by one each time.
input->height 5
i = 0, printing four dots for k = 3,2,1,0. printing one '#' for j=0
i = 1, printing three dots for k = 2,1,0. printing two '#' for j=0,1
i = 2, printing two dots for k = 1,0. printing three '#' for j=0,1,2
i = 3, printing one dots for k = 0. printing four '#' for j=0,1,2,3
i = 4, printing zero dots for k = . printing five '#' for j=0,1,2,3,4
答案 4 :(得分:0)
发布的解决方案似乎比预期的要复杂。您只需将所有行打印到所要求的高度,并找到在每行的开头打印'.'
的减少数的方法。
#include <stdio.h>
void draw_triangles(int height, char upper_left, char bottom_right)
{
if (height < 1 || height > 8)
return;
for (int row = 0; row < height; ++row)
{
// Calculate how many chars are in the left side of each row
int edge = height - row - 1;
for ( int i = 0; i < edge; ++i )
putchar(upper_left);
for ( int i = edge; i < height; ++i)
putchar(bottom_right);
putchar('\n');
}
}
int main(void)
{
// Let's test it
for (int i = 0; i <= 10; ++i)
{
printf("%d:\n", i);
draw_triangles(i, '.', '#');
puts("");
}
}