我编写的用于计算一组 3D 点的平均点的函数遇到了意外行为。
static inline Point3d
average_vertex_position( Vertex vertices[], int nPoints )
{
Point3d average = { 0.0, 0.0, 0.0 }; // Must be there to avoid accumulation
Point3d point;
int i;
for ( i = 0; i < nPoints; i++ )
{
point = vertices[i].position;
average.x += point.x;
average.y += point.y;
average.z += point.z;
}
average.x /= (double) nPoints;
average.y /= (double) nPoints;
average.z /= (double) nPoints;
return average;
}
// ...
Point3d average;
// ...
for ( j = i; j < nVertices; j++ )
{
// ...
average = average_vertex_position( vertices, nVertices );
// ...
}
对于每次迭代,average_vertex_position
的返回值都会累积,除非我明确添加初始化 Point3d average = { 0.0, 0.0, 0.0 };
。
如果之前的返回值是 Point3d( 10, 0, 20 )
而下一次运行应该返回 Point3d( 20, 10, 0 )
它会改为返回累积结果 Point3d( 30, 10, 20 )
。
最初我只有 Point3d average;
假设所有成员值(double
值)都将初始化为 0.0。我还假设 average
会在每次调用之间处于这个初始状态。我不明白为什么我需要显式初始化它?
我删除了我认为不相关的代码 - 但我可能是错的,在这种情况下,如果它没有包含足够的信息,我会进行更新。
最佳答案
这对于 auto
变量是正常的 - 如果没有明确说明,它们不会被初始化为 0。
旧值被重用纯属巧合,因为中间没有任何其他函数调用。如果你有它们,给定堆栈位置的内存将被覆盖并且你的值不同。
关于c - 非静态变量的累积返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9667319/