【问题标题】:Eclipse c++ not letting me use global variable?Eclipse c++ 不允许我使用全局变量?
【发布时间】:2019-05-05 13:09:36
【问题描述】:

我试图让这个递归程序计算它调用自己的次数,我打算使用一个全局变量来保持计数,但由于某种原因 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 时,它甚至都不会将其识别为变量,有人知道这是什么原因吗?

【问题讨论】:

    标签: c++ recursion global-variables fibonacci


    【解决方案1】:

    你的问题在这里:

    using namespace std;
    

    它引入了std::countfrom the algorithm header,所以现在count 是模棱两可的。这就是为什么人们被告知不要这样做using namespace std;。相反,删除该行并输入 std::cout 而不是 coutcinendl 也是如此)。

    【讨论】:

    • 谢谢你!我不知道这个!我最终只是更改了变量名称,因为它只是一个简短的小任务,但我很感激这些信息!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2011-09-04
    相关资源
    最近更新 更多