2011-10-16 83 views
3

有一個簡單的while循環,並試圖使其向一個for循環翻譯while循環成環

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

這裏是我的循環

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

爲什麼它不給相同的輸出?第一個會打印1248163264128,for循環打印137153163127

+2

增量'I * = 2'在'爲(I = 1; I <= 128; I * = 2)' – cpx

+0

條件在for循環是錯誤..配售我* = 2代替我的++解決你的問題.. –

回答

8

因爲你也在for循環中增加了i。在原來的while循環中,i從不增加。

試試這個:

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

不,一定要試試這個'for(i = 1; i <= 128; i * = 2)'!更糟的是,這個答案增強了這樣一個想法:for循環只能增加一個循環變量,而OP似乎已經有了。 –

+0

@ChristianRau看起來你從我以前的日子裏偶然發現了一篇文章。固定。 – Mysticial

13

for環雙打i,然後增加它。 while循環只能使其翻倍。

更改for循環到這一點:

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

while循環你沒有增加i,但在你的for循環使用的是

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

您遞增i與1和乘以i乘以2您的循環的每個迭代。這是你得到奇怪結果的原因。

請嘗試以下代碼,以獲得與while循環生成時相同的結果。

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