Eclipse C ++不让我使用全局变量吗?

时间:2018-12-04 06:59:42

标签: c++ recursion global-variables fibonacci

我正在尝试让此递归程序计算其自身调用的次数,并且我将使用全局变量来保持计数,但是eclipse出于某种原因无法识别它。这是我的代码:

#include <iostream>
#include <cstdlib>
using namespace std;

int count = 0;

int fib(long int);


int main()
{
    long int number;
    cout << "Enter a number => ";
    cin >> number;
    cout << "\nAnswer is: " << fib(number) << endl;
    return 0;
}

int fib (long int n)
{
    //cout << "Fibonacci called with: " << num << endl;
    if ( n <0 )
    {
        cout <<" error Invalid number\n";
        exit(1);
    }
    else if (n == 0 || n == 1)
        return 1;
    else{
        count++;
        return fib(n-1) + fib(n-2);}
    cout << count;

}

每当我最初声明count时,它甚至都不会将其识别为变量,有人知道它的原因吗?

1 个答案:

答案 0 :(得分:7)

您的问题在这里:

using namespace std;

它带来了std::count from the algorithm header,所以现在count是模棱两可的。这就是为什么人们被告知不要做using namespace std;的原因。相反,请删除该行,并放置std::cout而不是coutcinendl也是如此)。