2011-12-26 80 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语句,您可以避开该错误。