'else' without a previous 'if'

北城余情 提交于 2020-01-11 11:07:37

问题


I am just beginning to learn C programming, so I am not really on an advanced level. Bear with me!

I have this piece of code, and I guess that it is pretty easy to understand what I am trying to do. However I get an error saying the last else is called without an if before it.

I suspect that the problem is my if-else statement inbetween the if and else. How would you guys solve it?

int talet;
scanf("%d", &talet);

int i = 1;
while (i <= 99) {
  int a; {
    if (i % talet == 0 || talet == (i / 10) % 10 || talet == i % 10) {
      if (talet % 10 == 0)
        printf("\n");
      else
        continue;
    }
    printf("burr ");
    else
      printf("%d ", i);
  }
  i = i + 1;
}

回答1:


The problem is with your brackets. Indenting is important to understand where to open and close your brackets

int talet;
scanf("%d",&talet);

int i=1;
while(i<=99)
{
int a;

    if (i%talet==0 || talet==(i/10)%10 ||talet==i%10)
    {
             if (talet%10==0)
                  printf("\n");
             else
                  continue;

        printf("burr ");
    }
    else
    {
        printf("%d ",i);
    }
    i=i+1;
}



回答2:


Your problem is here:

}
    printf("burr ");  //<---
else
    printf("%d ",i);

You can't have any statements before the else block. So remove it or move it inside the else OR if block, something like this:

} else {
    printf("burr ");
    printf("%d ",i);
}



回答3:


The problem is that you have a printf outside the if brackets. Because of this, compiler thinks that the if statement finished. When it reaches the else, throws an error since there is no open if condition

You should have this

if (i%talet==0 || talet==(i/10)%10 ||talet==i%10)
{
    if (talet%10==0)
        printf("\n");
    else
        continue;

    printf("burr "); // <-- this was moved
}
else
    printf("%d ",i);



回答4:


try to keep your code-blocks as clean and readable as possible. This will prevent you from making mistakes.

You can write an if else Horstmann style:

if (condition)
{
    #statements
}
else
{
    #statements
}

or a bit more compact in TBS1 style:

if (condition) {
    #statements
} else {
    #statements
}

choose one you like, more styles in the comment provided by crashmstr (thanks to him), and stick to it. It WILL improve your code quality.



来源:https://stackoverflow.com/questions/28325228/else-without-a-previous-if

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!