当我尝试编译代码时,出现错误:else 没有前面的 if:
// Fibonacci series using recursion
#include <iostream>
using namespace std;
int fib (int n);
int main()
{
int n, answer;
cout << "\n\n\t\tEnter number to find: ";
cin >> n;
cout << "\n\n";
answer = fib(n);
if(n < 3 && n > 1)
cout << answer << " is the " << n;
cout << "nd 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";
}
else
cout << answer << " is the " << n;
cout << "th Fibonacci number\n";
return 0;
}
int fib (int n)
{
cout << "Processing fib (" << n << ")... ";
if (n < 3)
{
cout << "Return 1!\n";
return 1;
}
else
{
cout << "Call fib(" << n-2 << ") ";
cout << "and fib(" << n-1 << ").\n";
return(fib(n-2) + fib(n-1));
}
}
肯定是关键括号的问题:
int main()
{
int n, answer;
cout << "\n\n\t\tEnter number to find: ";
cin >> n;
cout << "\n\n";
answer = fib(n);
if(n < 3 && n > 1) {
cout << answer << " is the " << n;
cout << "nd 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";
}
}
else {
cout << answer << " is the " << n;
cout << "th Fibonacci number\n";
}
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)