您能告诉我为什么该程序的输出是ABBBCDE
吗?
这是我的考试问题。
#include <stdio.h>
int main (void)
{
int i;
for (i = 0; i < 2; i++)
{
printf ("A");
for (; i < 3; i++)
printf ("B");
printf ("C");
for (; i < 4; i++)
printf ("D");
printf ("E");
}
return 0;
}
答案 0 :(得分:5)
int
main (void)
{
int i;
for (i = 0; i < 2; i++)
{
printf ("A");
for (; i < 3; i++)
printf ("B");
printf ("C");
for (; i < 4; i++)
printf ("D");
printf ("E");
}
return 0;
}
与
相同int
main (void)
{
int i;
for (i = 0; i < 2; i++)
{
printf ("A"); // prints once
for (; i < 3; i++)
{
printf ("B"); // i = 0 at beginning, and loops until i = 2 => 3 times
}
printf ("C"); // prints once
for (; i < 4; i++)
{
printf ("D"); // i = 3 at beginning, so it prints once
}
printf ("E"); // prints once
} // next loop, i is already 4, which is more than 2, so first loop stops
return 0;
}
请不要这样写生产代码。
答案 1 :(得分:3)
如果您正确缩进代码,它将帮助您了解发生了什么:
#include <stdio.h>
int main(void)
{
int i;
for (i = 0; i < 2; i++)
{
printf("A"); // prints A 1 time, i is still 0
for (; i < 3; i++) // prints B 3 times, i will now be 3, the cycle ends
printf("B");
printf("C"); // prints C 1 time, this is not in any inner loop
for (; i < 4; i++) // prints D once, as i is 3, the cycle only runs once
printf("D");
printf("E"); // again prints E once
} // as i is 4 the cycle will end, the condition is i < 2
return 0;
}
答案 2 :(得分:0)
因为您有一个for循环,用于检查i是否小于3。它从零开始,零小于3,所以它打印B一次,然后将其加到i上,而i变为1,但仍小于3,所以它打印了另一个B。然后它对i进行了广告,使其变成了2 ,但仍小于零,这使其第三次打印B。然后它向i添加另一个,使其等于3,且不少于3,因此通过键入C继续执行程序。