2011-12-26 103 views
0

我正在嘗試這個基本代碼塊來熟悉條件。我不認爲我錯過了括號或任何東西,但是我得到一個錯誤,我在第二個else子句之前錯過了一個語句,但我不明白這一點。之前沒有聲明

#include stdio.h; 
main() 
{ 
    int a = 2; 
    int b = 4; 
    int c = 6; 
    int d = 8; 
    if (a > b) 
    { 
     a = a - 1; 
     printf("a = %d ", a); 
    } 
    else 
    { 
     if (b >= c) 
     { 
      b == b ? : 2; 
     } 
     printf("b = %d ", b); 
    } 
    else 
    { 
     if (c > d) 
     { 
      c = c + d; 
     } 
    } 
    else 
    { 
     d = d/2; 
    } 
} 

有什麼建議嗎?

+0

downvote似乎沒有必要... – 2011-12-26 03:44:24

回答

1

此代碼是一樣的你,縮進在幾個比較正統的款式之一。

int main(void) 
{ 
    int a = 2; 
    int b = 4; 
    int c = 6; 
    int d = 8; 

    if (a > b)  
    { 
     a = a - 1; 
     printf("a = %d ", a); 
    } 
    else 
    { 
     if (b >= c) 
     { 
      b == b ? : 2; // Syntax errors here too (and statement with no effect?) 
     } 
     printf("b = %d ", b); 
    } 
    else 
    { 
     if (c > d) 
     { 
      c = c + d; 
     } 
    } 
    else 
    { 
     d = d/2; 
    } 
} 

正如你所看到的,有連續3項else條款,在這裏你只允許一個。

還有其他語法問題。

3

如果你正確地縮進代碼,你會看到這個問題:

} else { 
    if (c > d) { 
     c = c + d; 
    } 
} else { 
    d = d/2; 
} 
+0

我沒有看到問題?如果在其他內部,而其他人是自足的? – 2011-12-26 02:32:49

+0

@SonnyOrdell:不;因爲在中間有一個額外的'}',所以'if'不與'else'一起使用。注意縮進。 – SLaks 2011-12-26 03:12:54

+0

if是在else之內,因爲c = c + d被括在圓括號中,並且whol; e如果block在else子句的括號內? – 2011-12-26 03:29:14

0

在C語言程序 如果..別的...這樣

if(condition 1) 
     statement1; 
    else if(condition 2) 
     statement2; 
    else if(condition 3) 
     statement3; 
    else 
     statement4; 
1

C的結構只能有一個else語句的if語句。相反,它可能有多個elseif語句。爲if語句添加更多數量的else語句會報告語法錯誤。

程序中的錯誤指出第二個else在它之前必須有一個if。 因此,將所有中間else語句與嵌套if轉換爲elseif語句。保留最後的else語句,您可以避開該錯誤。