C ++,多次调用时输出不同的函数

时间:2016-05-19 12:33:08

标签: c++ function

我有以下代码:

int countLatticePoints(const double radius, const int dimension) {
static std::vector<int> point {};
static int R = static_cast<int>(std::floor(radius));
static int latticePointCount = 0;

for(int i = -R; i <= R; i++) {

    point.push_back(i);

    if(point.size() == dimension) {
        if(PointIsWithinSphere(point,R)) latticePointCount++;
    } else {
        countLatticePoints(R, dimension);
    }

    point.pop_back();
}

return latticePointCount;
}

当我调用countLatticePoints(2.05,3)时,我得到的结果是正确的13。现在我改变参数然后调用countLatticePoints(25.5,1)我得到51这也是正确的。

现在当我在主程序中紧接着调用countLatticePoints(2.05,3)和countLatticePoints(25.5,1)时,我得到13然后是18(而不是51),我真的不明白我是什么#39;我做错了吗?当我单独调用每一个而没有另一个时,我得到了正确的结果但是当我一个接一个地调用这些函数时,我的结果发生了变化。

2 个答案:

答案 0 :(得分:4)

你误用了static

第二次调用该函数时,会将其他值推送到point

编辑:我没有发现递归。这会使事情变得更复杂,但static仍然是错误的答案。

我创建一个'state'对象,并将该函数拆分为两个。一个递归,并引用'state'对象,另一个初始化状态对象并调用第一个。

struct RecurState 
{
  std::vector<int> point;
  int latticePointCount

  RecurState() : latticePointCount(0)
  {
  }
}

外部功能:

int countLatticePoints(const double radius, const int dimension) 
{
  RecurState state;
  return countLatticeRecurse(radius, dimension, state)
} 

递归函数

int countLatticeRecurse(const double radius, const int dimension, RecurseState &state)
{
  ...
}  

答案 1 :(得分:1)

本地静态变量仅在第一次函数调用时初始化一次。

相关问题