C语言 'else' 没有前面的 'if'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28325228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'else' without a previous 'if'
提问by Diaco
I am just beginning to learn C programming, so I am not really on an advanced level. Bear with me!
我刚刚开始学习 C 编程,所以我并不是真正的高级水平。忍着我!
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.
我有这段代码,我想很容易理解我想要做什么。但是我收到一个错误,说最后一个 else 被调用而没有 if 在它之前。
I suspect that the problem is my if-else statement inbetween the if and else. How would you guys solve it?
我怀疑问题是我在 if 和 else 之间的 if-else 语句。大家会怎么解决?
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;
}
回答by Rizier123
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 块之前不能有任何语句。因此,将其删除或将其移动到 else OR if 块中,如下所示:
} else {
printf("burr ");
printf("%d ",i);
}
回答by phil652
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;
}
回答by Claudio Redi
The problem is that you have a printfoutside the ifbrackets. Because of this, compiler thinks that the ifstatement finished. When it reaches the else, throws an error since there is no open ifcondition
问题是你printf在if括号外有一个。正因为如此,编译器认为if语句完成了。当它到达 时else,由于没有打开if条件而引发错误
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);
回答by Christian
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 else Horstmann 风格:
if (condition)
{
#statements
}
else
{
#statements
}
or a bit more compact in TBS1 style:
或者更紧凑的 TBS1 风格:
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.
在crashmstr提供的评论中选择一个你喜欢的,更多的样式(感谢他),并坚持下去。它将提高您的代码质量。

