[英]confusion with evaluation of the condition and the steps of a for loop
void draw_diamond(int n)
{
int mid_pos = ceil((double)n / 2);
int left_spaces = mid_pos-1;
int line_stars = 1;
putchar(10);
//printing from top through the middle of the diamond
for(line_stars, left_spaces ; line_stars <= n; line_stars+=2, left_spaces--);
{
//printing the left_spaces
for(int i=1; i<=left_spaces; i++)
putchar(32);
//printing the line_stars
for(int i=1; i<=line_stars; i++)
putchar('*');
putchar(10);
}
... ...
I have problem here, when I step into
the for loop
for the first time, nothing happens, for the second one for loop step is applied
eg: if I pass 1 to n
then: 我在这里遇到问题,当我
step into
for loop
时,什么也没发生,因为第二个for loop step is applied
例如:如果我pass 1 to n
则:
mid_pos =1; mid_pos = 1; left_spaces=0;
left_spaces = 0; line_stars=1;
line_stars = 1;
it goes inside the loop with: left_spaces=-1; 它进入循环:left_spaces = -1; line_stars=3;
line_stars = 3;
the for loop
prints 3 stars where it should print just 1. for loop
打印3个星号,该区域应仅打印1个星号。
I'm confused, I'd appreciate it if any one could help. 我很困惑,如果有人可以帮忙,我将不胜感激。
Uh oh, watch out for the sneaky semicolon: 哦,小心那些偷偷摸摸的分号:
for(line_stars, left_spaces ; line_stars <= n; line_stars+=2, left_spaces--);
^
|
This ends your for
statement. 这样就结束了您的
for
语句。 The loop will just run until line_stars
is greater than n
. 循环将一直运行,直到
line_stars
大于n
为止。 By the end, line_stars
will now equal 3 (because it is increased by 2). 到最后,
line_stars
现在将等于3(因为它增加了2)。 left_spaces
will be -1. left_spaces
将为-1。
Now the rest of your code which is enclosed by curly brackets will execute. 现在将执行大括号括起来的其余代码。 The first
for
loop won't run at all, but the second one will run from 1 until line_stars
and, as we know, line_stars
is 3, so we get 3 stars printed out. 第一个
for
循环根本不会运行,但是第二个循环将从1开始运行,直到line_stars
并且正如我们所知, line_stars
为3,所以我们打印了3个星星。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.