将while循环转换为for循环

Tua*_*yen 3 c for-loop while-loop

有一个简单的while循环并尝试使其成为for循环

i=1
while(i<=128)
{     printf("%d",i);
   i*=2;
}
Run Code Online (Sandbox Code Playgroud)

这是我的for循环

for (i=1;i<=128;i++)
{ 
   printf("%d",i);
   i*=2;
}
Run Code Online (Sandbox Code Playgroud)

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

ick*_*fay 13

for环双打i,然后增加它.在while仅环双打吧.

for循环更改为:

for (i=1;i<=128;i*=2) {
    printf("%d", i);
}
Run Code Online (Sandbox Code Playgroud)


Mys*_*ial 8

因为你也在ifor循环中递增.在原始的while循环中,i永远不会增加.

试试这个:

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