【问题标题】:error C2106: '=' : left operand must be l-value in Fibonacci sequence by dynamic programming in C++错误 C2106:'=':左操作数在 C++ 中通过动态编程必须是斐波那契数列中的左值
【发布时间】:2014-01-29 09:10:06
【问题描述】:

我正在尝试编写一个通过动态编程方法生成斐波那契数列的程序,如下所示。

#include<iostream>
#include<ctime>

int fib(int index)
{
    int memo[] = {0};
    memo[0] = 0;
    memo[1] = 1;
    for(int i = 2; i <= index; i++)
    {
        fib(index) = fib(index - 1) + fib(index - 2);   //error comes here
    }
    return fib(index);
}
int main()
{   
    time_t start, end, diff;
    int index;
    std::cout << "Please, enter the index of fibonacci sequence" << std::endl;
    std::cin >> index;
    start = time(NULL);
    std::cout << "calculating...." << std::endl << fib(index) <<std::endl;
    end = time(NULL);
    diff = (time_t)difftime(end, start);
    std::cout << "Time elapsed: " << diff << std::endl;
    return 0;
}

但是,在fib(index) = fib(index - 1) + fib(index - 2); 行中,我遇到了错误

error C2106: '=' : left operand must be l-value

所以,请告诉我我在该行中做错了什么。提前致谢。

【问题讨论】:

  • 可能应该有一个 memo[index] 而不是 fib(index)
  • 不要分配给fib(index)

标签: c++ fibonacci lvalue


【解决方案1】:

正如其他人已经指出的那样,您不能分配给fib(index)。有通过返回引用或指针的解决方法。

但是程序本身是错误的,因为它进入了无限循环。线

fib(index) = fib(index - 1) + fib(index - 2);  

如果 index > 1 则继续启动 fib(index)。使用 DP 解决斐波那契的正确方法是

int fib(int n)
{
  int a = 0, b = 1, c, i;
  if( n == 0)
    return a;
  for (i = 2; i <= n; i++)
  {
     c = a + b;
     a = b;
     b = c;
  }
  return b;
}

【讨论】:

  • 我知道那种方法。但是,有人告诉我通过有效地使用递归来生成斐波那契数列。
  • @yuvi 你为什么不在你的问题中添加这个。如果您想进行递归,如果您将数组替换为std::vector,那么您之前发布的内容将起作用
【解决方案2】:

你必须像这样引入一个临时变量:

int result = 0;
for(int i = 2; i <= index; i++)
{
    result = fib(index - 1) + fib(index - 2);   //error comes here
}
return result;

但这只是技术解决方案。正如 Bala 指出的那样,您的算法本身不起作用。

如果您正在寻找递归解决方案,这可能是一个解决方案:

int fib(int index)
{
    switch(index) {
    case 0:
        return 0;
    case 1:
        return 1;
    default:
        return fib(index - 1) + fib(index -1);
    }
}

对于真正的动态解决方案,您可以将所有计算值存储到静态备忘录中,如果它已经存在,则可以重复使用。

int fib(int index)
{
    // Stores fib for given index
    static std::map<int, int> memo;

    if (index == 0) return 0;
    else if (index == 1) return 1;
    else {
       auto it = memo.find(index);
       if (it == memo.end()) {
           int r = fib(index - 1) + fib(index -2);
           memo[index] = r;
       } else return *it;
    }
}

【讨论】:

  • 你错过了 switch-case 的右括号:p
【解决方案3】:

您正在分配一个左值(这是int fib(int) 返回的值)。就像错误消息状态一样。

还要注意int memo[] = {0}; 创建一个大小为1 的数组,因此超出索引0 的写入是无效的。

【讨论】:

  • 嘿,谢谢。我将其修改为int memo[] = {}。但是,然后它返回错误error C2466: cannot allocate an array of constant size 0
  • @yuvi 您无法在 C++ 中轻松调整数组的大小。使用std::vector
  • 不要使用裸数组,使用 std::vector 和 memo[0] = 1;
  • 我使用向量而不是数组。现在,程序编译成功;但它没有执行。它指出Expression: vector subscript out of range.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-29
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 2013-11-30
  • 1970-01-01
相关资源
最近更新 更多