簡體   English   中英

while循環在這里如何工作?

[英]How does the while loop work here?

盡管我有C的基本概念,但我遇到了以下代碼。我仍然了解以下代碼的邏輯。

  1. 循環如何終止,循環何時終止-在什么條件下?

  2. 最后, counter變為零,但為什么循環不繼續以-1,-2執行並終止呢?

碼:

#include <stdio.h>

void func(void);
static int count = 5;
int main()
{
    while (count--)
    {
        func();
    }
    return 0;
}

void func(void)
{
    static int i = 5;
    i++;
    printf("i is %d and count is %d\n", i, count);
}

輸出:

i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0

while(term)

當term(condition / variable / function)求值為0時,while循環終止。

count--返回count的值,然后遞減。

因此,當count--返回零循環時終止。 當count的值為0時將是該值。另請參見注釋。

C將0設為false,其余部分設為true,因此,當條件評估為false(0)時,while循環將中斷。

在這里,當count變為0時,循環終止,因為在C中,0在Java(布爾類型)中的作用類似於false,因此條件為false。 循環退出。

當count =

0-循環條件為假

非0-循環條件為true

條件的的while循環, count-- ,計算結果為1時的值count1的表達式的求值之前。 表達式求值的副作用是count的值減1 ,即它的值變為0

這就是為什么你看到

i is 10 and count is 0

作為輸出。

下次評估循環的條件時,表達式的值為0 ,而count的值設置為-1 由於表達式的值為0 ,因此循環的執行停止。

count--是 -decrement 因此, countwhile條件下不會立即減少。 此后遞減(僅在評估while條件之后)。 因此,當count = 1並且count--完成時, while繼續運行。 但是在進入whilecount becomes 0 ,因此,下次條件評估到達時, while中斷。

簡單來說, count is equal to 5並且您希望它運行5次迭代(在簡單流程下),因此它運行4 to 0 如果您想以其他方式解決問題,可以嘗試一下,自己看看

while( 0 != count )
{
   func() ;
   count-- ;
}

在C和C ++中,如果使用表達式代替條件,則任何導致零(0)的表達式都將被評估為false。 看-

if(0){
  //never reached; never executed
}  

類似地,表達式中的任何非零值都將被評估為true

if(5){
   //always reached and executed
}  

這個事實適用於while-loop條件-

int i = 5;
while(i){
  //do something

  i--;
}

問題1:循環如何終止,循環在什么條件下終止。

ans: while循環從count = 5開始。由於count非零,所以滿足了循環條件。但是由於count-,count值立即減1並變為count = 4。 所以輸出是

我是6,數是4

直到計數= 1,它繼續。計數= 1也滿足循環條件。 但是立即計數-發生,現在計數= 0。 所以輸出是

我是10,計數是0

因此,在下一個檢查循環條件不滿足時(計數= 0),循環終止。

問題2:最后一個計數器變為零,但是為什么循環不繼續存在於-1,-2而是終止呢?

回答:當循環條件變為零時,它將創建一個FALSE條件。 因此它在那里終止。

注意:條件塊中只有零值會終止循環。 如果小於零,則不會。

檢查一下。

void func(void);
static int count = -5;
main()
{
    while (count++)
    {
        func();
    }
    return 0;
}

void func(void)
{
    static int i = 5;
    i++;
    printf("i is %d and count is %d\n", i, count);
}

創建輸出為

i is 6 and count is -4
i is 7 and count is -3
i is 8 and count is -2
i is 9 and count is -1
i is 10 and count is 0

while表達式是布爾值 整數表達式count--因此隱式地轉換為布爾值,這樣任何非零值都為true而零為false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM