将while循环转换为for循环

时间:2011-10-16 02:26:10

标签: c for-loop while-loop

有一个简单的while循环并尝试将其设为for循环

i=1
while(i<=128)
{     printf("%d",i);
   i*=2;
}

这是我的for循环

for (i=1;i<=128;i++)
{ 
   printf("%d",i);
   i*=2;
}

为什么不给出相同的输出?第一个会打印1248163264128,for循环打印137153163127

4 个答案:

答案 0 :(得分:13)

for循环加倍i然后递增它。 while循环只会加倍。

for循环更改为:

for (i=1;i<=128;i*=2) {
    printf("%d", i);
}

答案 1 :(得分:8)

因为您还在for循环中递增i。在原始的while循环中,i永远不会递增。

试试这个:

for (i=1; i<=128; i*=2)  //  Remove i++, move the i*=2 here.
{
    printf("%d",i);
}

答案 2 :(得分:3)

for (i=1;i<=128;i*=2)
{ 
  printf("%d",i);    
}

答案 3 :(得分:1)

while循环中,您没有增加i,而是在您正在使用的for循环中

for (i=1;i<=128;i++)
{
printf("%d",i);
    i*=2;
}

在循环的每次迭代中,您使用一个递增i并将i乘以2。这就是你得到奇怪结果的原因。

尝试以下代码获得与while循环生成相同的结果。

for (i = 1; i <= 128; i *= 2)
{
printf("%d",i);        
}
相关问题