(编辑:这是一个完全重新设计的答案。请参阅评论。感谢您并为“争议”感到抱歉。)
{
因为您没有}
在main
.
首先让我们看一下代码的内部部分:
if(n < 3)
cout << answer << " is the " << n;
cout << "st Fibonacci number\n";
else
cout << answer << " is the " << n;
cout << "rd Fibonacci number\n";
当前的缩进是“错误的”并且具有误导性。如果你将它复制粘贴到代码编辑器中并使用自动格式化(自动缩进就足够了),你会得到:
if(n < 3)
cout << answer << " is the " << n;
cout << "st Fibonacci number\n";
else
cout << answer << " is the " << n;
cout << "rd Fibonacci number\n";
它向您展示了代码的真正“含义”。为了清楚起见,添加大括号和空行后:
if(n < 3)
{
cout << answer << " is the " << n;
}
cout << "st Fibonacci number\n";
else
{
cout << answer << " is the " << n;
}
cout << "rd Fibonacci number\n";
如您所见,只有第一个cout
语句受if
. 第二个将始终被执行。然后是一个else
遵循“普通”、“无条件”语句的语句,而不是“有条件的”语句/块(整个语句块也是一个语句)。
要修复此部分,您必须将所有条件语句包装在大括号中:
if(n < 3)
{
cout << answer << " is the " << n;
cout << "st Fibonacci number\n";
}
else
{
cout << answer << " is the " << n;
cout << "rd Fibonacci number\n";
}
或更紧凑的风格:
if(n < 3) {
cout << answer << " is the " << n;
cout << "st Fibonacci number\n";
} else {
cout << answer << " is the " << n;
cout << "rd Fibonacci number\n";
}
这样完整的块语句是有条件的。
既然“内部”if-else 部分已经固定,让我们来看看“外部”if-else:
if(n < 3 && n > 1)
cout << answer << " is the " << n;
cout << "nd Fibonacci number\n";
{
/* ... fixed inner if-else ... */
}
else
cout << answer << " is the " << n;
cout << "th Fibonacci number\n";
让我们再次使用代码格式化程序:
if(n < 3 && n > 1)
cout << answer << " is the " << n;
cout << "nd Fibonacci number\n";
{
/* ... fixed inner if-else ... */
}
else
cout << answer << " is the " << n;
cout << "th Fibonacci number\n";
真正的含义现在应该很清楚了(这里使用紧凑的样式):
if(n < 3 && n > 1) {
cout << answer << " is the " << n;
}
cout << "nd Fibonacci number\n";
{
/* ... fixed inner if-else ... */
}
else {
cout << answer << " is the " << n;
}
cout << "th Fibonacci number\n";
中间的有趣块(大括号内的代码但不直接跟在if
/后面else
)实际上是一个匿名块,它只是引入了一个内部范围(内部定义的变量在关闭之后将不再存在}
)。它可以看作是一个简单的语句(无条件),就像cout << "nd Fibonacci number\n";
它上面的一样。
再一次,修复很明显:
if(n < 3 && n > 1) {
cout << answer << " is the " << n;
cout << "nd Fibonacci number\n";
/* ... fixed inner if-else ... */
} else {
cout << answer << " is the " << n;
cout << "th Fibonacci number\n";
}