C++,多次调用时输出不同的函数
C++, different function output when called multiple times
我有以下代码:
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)
{
...
}
本地静态变量只在第一次函数调用时初始化一次。
相关文章:
- 如何从void函数输出字符串
- 简化C++包括变量名称和函数输出的模式
- 素数检查 C++ 函数输出非素数的数字
- 在C++目录中搜索文件的函数输出中出错
- 用于计算周长和面积的程序,而不是从 void 函数输出值
- 使用 if/else if 的函数输出问题
- (c++) 返回和函数输出之间的错误
- 使用函数输出最高平均值
- 为什么另一个函数输出错误的值
- C++函数输出泛型结构
- 在 c++11 中,是否仍然需要传入对接受函数输出的对象的引用
- 虚拟函数输出奇怪的值
- 将打印到控制台的函数输出重定向到字符串
- c++ 将函数输出重定向到编译的程序输入,反之亦然
- 未修改 CUDA 内核函数输出变量
- iomanip意外影响ctime函数输出
- 素数分解函数输出
- 继承构造函数输出
- 多维数组函数输出垃圾
- 递归函数-输出不正确