【问题标题】:Expected expression before '||' token'||' 之前的预期表达式令牌
【发布时间】:2013-11-13 19:08:21
【问题描述】:

我正在学习C,遇到错误信息“Expected expression before || token”。

#include <stdio.h>
char calculate_Easter_date(int y);

int main()
{
    int year;
    char sol [80];
    while (1)
    {
        scanf("%d", &year);
        if (year == EOF){
                break;
        }
        sol = calculate_Easter_date(year);
        printf("%s\n", sol);
    }
    return 0;
}

char calculate_Easter_date(int y)
{
    char buf[80];
    int g = (y % 19) + 1;
    int c = (y / 100) + 1;
    int x = (3 * c / 4) - 12;
    int z = ((8 * c + 5) / 25) - 5;
    int d = (5 * y / 4) - x - 10;
    int e = (11 * g + 20 + z - x) % 30;
    if ((e == 25) && (g > 11)) || (e == 24){
        e ++;
    }
    int n = 44 - e;
    if (n < 21){
        n += 30;
    }
    int n = (n + 7) - ((d + n) mod 7);
    if (n > 31){
        sprintf(buf, "%d APRIL %d", y, n - 31);
        return buf;
    }
    else{
        sprintf(buf, "%d MARCH %d", y, n);
        return buf;
    }
}

【问题讨论】:

  • calculate_Easter_date() 的第 8 行结束括号过多

标签: c error-handling compiler-errors conditional-statements


【解决方案1】:

你需要:

if (((e == 25) && (g > 11)) || (e == 24)) {
        e ++;
    }

注意多余的括号。

【讨论】:

    【解决方案2】:

    在 C 和 C++ 中,if 语句采用这种形式:

    if (expression) statement;
    

    语句当然可以是一个块,由{} 分隔,但这不是这里的问题。

    请注意,要检查的表达式必须用括号括起来。

    所以这一行:

    if ((e == 25) && (g > 11)) || (e == 24){
    

    是罪魁祸首。

    让我突出显示其中的一部分

        +-------+    +------+
        |       |    |      |
        v       v    v      v
    if ((e == 25) && (g > 11)) || (e == 24){
       ^                     ^
       |                     |
       +---------------------+
    

    下面的高亮显示了分隔表达式的括号所在的位置,这意味着你的 if 语句如下:

    if (expression) || (e == 24){
                    ^
                    +-- start of the statement
    

    要解决这个问题,您需要添加另一层括号来包含额外的位:

       +------------- add these ------------+
       |                                    |
       | +-------+    +------+              |
       | |       |    |      |              |
       v v       v    v      v              v
    if (((e == 25) && (g > 11)) || (e == 24)){
        ^                     ^
        |                     |
        +---------------------+
    

    【讨论】:

      猜你喜欢
      • 2012-10-30
      • 1970-01-01
      • 2020-10-30
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 2013-11-12
      • 1970-01-01
      相关资源
      最近更新 更多