Because you didn't properly use braces ("curly brackets", {
and }
) in your main
.
First let's take this inner part of the code:
if(n < 3)
cout << answer << " is the " << n;
cout << "st Fibonacci number\n";
else
cout << answer << " is the " << n;
cout << "rd Fibonacci number\n";
That current indentation is "wrong" and misleading. If you copy-paste it into a code editor and use auto-formatting (auto-indent will suffice), you'll get:
if(n < 3)
cout << answer << " is the " << n;
cout << "st Fibonacci number\n";
else
cout << answer << " is the " << n;
cout << "rd Fibonacci number\n";
which shows you the real "meaning" of the code. After adding braces and blank lines for clarity:
if(n < 3)
{
cout << answer << " is the " << n;
}
cout << "st Fibonacci number\n";
else
{
cout << answer << " is the " << n;
}
cout << "rd Fibonacci number\n";
As you can see, only the first cout
statement is conditioned by the if
. The second one will always be executed. Then comes an else
that follows a "plain", "unconditional" statement, not a "conditioned" statement/block (a block of statement(s) as a whole is a statement too).
To fix this part you must wrap all the conditioned statements in braces:
if(n < 3)
{
cout << answer << " is the " << n;
cout << "st Fibonacci number\n";
}
else
{
cout << answer << " is the " << n;
cout << "rd Fibonacci number\n";
}
or in a more compact style:
if(n < 3) {
cout << answer << " is the " << n;
cout << "st Fibonacci number\n";
} else {
cout << answer << " is the " << n;
cout << "rd Fibonacci number\n";
}
such that the full block-statement is conditioned.
Now that the "inner" if-else part is fixed, let's take the "outer" 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";
Let's use a code formatter again:
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";
The real meaning should now be clear (using compact style here):
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";
The funny block alone in the middle (code inside braces but not directly following an if
/else
) is actually an anonymous block, which just introduces an inner scope (variables defined inside will not exist anymore after the closing }
). It can be see as a plain statement (unconditional), just like the cout << "nd Fibonacci number\n";
just above it.
Once again, the fix is obvious:
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";
}