int i;
main()
{
int t;
for ( t=4;scanf("%d",&i)-t;printf("%d\n",i))
printf("%d--",t--);
}
如果输入为 0、1、2、3,则输出为:
4--0
3--1
2--2
请解释程序的输出。我无法弄清楚为什么输出是这样的。循环在这个程序中是如何工作的?为什么不先打印for循环中的printf?
将for
循环转换为等效while
循环。表单的for
循环
for (initialize; condition; increment)
{
body;
}
可以等效地写为:
initialize;
while (condition)
{
body;
increment;
}
注意increment
语句是如何在循环底部结束的。它在循环体之后执行,就在开始循环的下一次迭代之前。
所以你的循环变成了这样:
int i;
main()
{
int t;
t = 4;
while (scanf("%d",&i) - t)
{
printf("%d--", t--);
printf("%d\n", i));
}
}
这有帮助吗?
最棘手的部分是循环条件。循环将在其条件变为 0 时退出。返回读入的项目数,这里每次读scanf
入的项目数为 1 。%d
如果scanf
每次都返回 1,则循环在t
命中 1 时退出。
for
执行完循环体后调用第三步操作符。
说到你的例子,这...
for ( t=4; // initialization statement
scanf("%d",&i)-t; // check statement; if `false`, the loop is finished
printf("%d\n",i)) // step statement, usually advances an iteration one step
printf("%d--",t--);
...像这样走过:
t
.scanf
,将结果(0)赋值给i
,检查1(的结果scanf
)是否等于t
;现在不是。printf
为 postdecremented做t
(它打印4--
)printf
中提到,打印for
0\n
scanf
,将结果 (1) 分配给i
,检查 1 是否等于t
(现在是 3,因为它是递减的)。printf
为 postdecremented做t
(它打印3--
)printf
中提到,打印for
1\n
scanf
,将结果 (2) 分配给i
,检查 1 是否等于t
(现在是 2,因为它是递减的)。printf
为 postdecremented做t
(它打印2--
)。printf
中提到,打印for
2\n
scanf
,将结果(3)赋值给i
,检查 1 是否等于t
(现在是 1)。'scanf' 返回分配的项目数。对于您的输入,scanf 为每个输入返回 1(因为您想一次读取一个 '%d' 的项目)。变量 t 从 4 开始。现在,每次迭代的“for”条件变为:1-4、1-3、1-2 和 1-1 (=0),因此在“1-1”的情况下没有进入循环体(因为条件结果为0,表示为假)并终止循环。希望它能解释你的程序的结果。