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

C++, different function output when called multiple times

本文关键字:函数 输出 调用 C++      更新时间:2023-10-16

我有以下代码:

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),我真的不明白我做错了什么?当我单独调用每个函数而不调用另一个函数时,我会得到正确的结果,但当我一个接一个地调用函数时,结果会发生变化。

您滥用了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)
{
  ...
}  

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