2014-01-09 46 views
1

我在C中有一個非常簡單的問題。我試圖編寫一個簡單的程序,在10100之間輸出10的倍數(包括:在閉區間[10,100] )跳過3070並垂直輸出值。ac迭代,同時跳過do while while循環中的給定值

這裏是我的代碼:

#include<stdio.h> 
main() 
{ 
    int i=10; 
    do { 
    if(i==30||i==70) 
     continue; 

    printf("\n %d",i); 
    i++; 
    } while(i<100); 

    return 0; 
} 

程序停止在29跳過30,並繼續成爲永無止境的循環。哪裏不對?

+0

http://msdn.microsoft.com/en-us/library/0ceyyskb.aspx – pcnThird

+0

很多人爲這一個的聲望點打炮...... –

回答

0

請勿使用continue。相反,打印出的值只要!=3070。同樣重複10而不是1以輸出倍數10

#include<stdio.h> 
main() 
{ 
    int i = 10; 

    do 
    { 
     if (i != 30 && i != 70) 
      printf("\n %d", i); 

     i += 10; 

    } 
    while (i <= 100); // if you want to print 100 

    return 0; 
} 

輸出:

10 
20 
40 
50 
60 
80 
90 
100 

使用while (i <= 100);如果你需要同時打印100

+1

非常感謝你,這真的很有幫助 – drewjulo

3

問題是,當您點擊if聲明時,您正在跳過i的增量。所以你永遠不會達到100!

#include<stdio.h> 
main() 
{ 
    int i=10; 
    do { 
    if(i==30||i==70) 
     continue;  //!!!! This will skip the i increment 

    printf("\n %d",i); 
    i++; 
    } while(i<100); 

    return 0; 
} 

我建議for循環:

main() 
{ 
    for (i = 10; i < 100; i++) { 
    if(i==30||i==70) 
     continue;   // The for loop will do the i++ on the "continue" 

    printf("\n %d",i); 
    } 

    return 0; 
} 
1

i達到30 continue語句移回到循環的開始。

因此循環繼續不斷,因爲i不會從這一點遞增。

0

它永遠循環,因爲你continue但不增加i。

if(i==30||i==70) { 
    i++; 
    continue; 
} 

或者你可以使用一個for循環像這樣,

#include<stdio.h> 
int main() 
{ 
    int i=10; 

    for (; i < 100; i++) 
    { 
    if(i==30 || i==70) { 
     continue; 
    } 
    printf("\n %d",i); 
    } 

    return 0; 
} 
1

您的代碼做什麼它寫做。 continue跳過增量指令,所以值達到30並卡在那裏。將增量移動到循環體的起始處,或者更好的是,使用for而不是while

0

原因是i在do.while內部30之後從未增加。你需要增加它。

if (i == 30 || i == 70){ 
    i++; 
    continue; 
} 
2

mbratch正確地指出你的問題,但你可能要考慮一個for循環爲這樣的事情。它會防止這個特殊問題,因爲增量是自動的。

我不會做整個事情給你,因爲你明顯是想學習,但是這應該讓你開始:

for (i=0; i<100; i+= 1) 

你必須改變一些數字的該線,但希望你會明白他們改變他們的意思。