2011-10-13 80 views

回答

1

使用if的條件知道該數字是否小於或不。如果是的話,只需在裏面使用break聲明,這會讓你走出循環。 Learn more about break statement from MSDN.

+0

@GregS:正確。但是,讓我們不要勺喂OP。讓他從鏈接或其他來源閱讀關於「break」聲明的想法後再想一想。 – Mahesh

+0

好的,我和你在一起。刪除。 –

1

那麼,什麼是負數?這是一個小於零的數字(稱爲x),或者象徵性地爲x < 0。如果x小於零,那麼這是真的。如果不是,那麼它是錯誤的。

你可以無限循環,當滿足此條件時突破:

while (1) { 
    if (x < 0) { 
    break; 
    } 

    ... 
} 

但我更願意只使用條件相反的while循環本身:

while (x >= 0) { 
    ... 

雖然條件是真的,那麼循環繼續。當它是假的(並且你的原始條件是真的,因爲這兩個是相反的),循環中斷。

0

不要將變量定義爲無符號變量。正如其他答案中所建議,使用if語句並與if語句斷開。

例如:

int main(void) 
{ 
int i; 
while(1){ 
/*here write an statement to get and store value in i*/ 
    if(i<0) 
    { 
    break; 
    } 
/*other statements*/ 
    return(0); 
    } 
} 
1
int i = -1; 
do 
{ 
    i = magic_user_input(); 
    //simple enough? get a decent programming book to get the hang of loops 
} 
while(i > -1) 

編輯:對不起,我的錯誤: '我' 未正確申報:)現在它應該是蠻好用的