gpt4 book ai didi

C++ 递归错误

转载 作者:行者123 更新时间:2023-11-28 08:30:03 24 4
gpt4 key购买 nike

我有以下递归代码,但它没有按预期运行(请参阅下面的详细信息):

R3Intersection ComputeIntersectionNode(R3Ray *ray, R3Node *node)
{
R3Intersection closest_inter;
R3Intersection child_inter;
R3Intersection shape_inter;

double least_t = DBL_MAX;

// check for intersection with shape
if(node->shape != NULL)
{
shape_inter = ComputeIntersectionShape(ray, node->shape);
if(shape_inter.hit == 1)
closest_inter = shape_inter;
}

// go through all the children and for each child, compute
// the closest intersection with ray
for(int i = 0; i < node->children.size(); i++)
{
// compute intersection with children[i] and ray
child_inter = ComputeIntersectionNode(ray, node->children[i]);

// if there's an intersection with the child node and
// it is the closest intersection, set closest intersection
if(child_inter.hit == 1 && fabs(child_inter.t) < fabs(least_t))
closest_inter = child_inter;
}

return closest_inter;
}

这个ComputeIntersectionNode(...),除了递归调用之外,在程序中也是针对多条射线调用的。为了测试这个函数,我运行了 4 个 rays 和 4 个 nodes(或者更准确地说,一个 node 类型的 root code>,它没有 shape,但有 4 个 children,每个 child 都有一个 shape)。为了进行测试,每个 ray 恰好与一个 node/shape 相交。

当我在 GDB 中为第一个 ray 运行代码时,它首先通过没有 shape 的代码传递 root code>,所以它直接转到 children。它正确计算第一个 child 的交集并正确设置 closest_inter 变量,它返回到最高级别的递归和 child_inter 以及 closest_inter 在这里设置 child_inter.hit = 1;

然后,处理第二个 child 。 ComputeIntersectionShape(...) 不返回与第二个 child 的交集 (shape_inter.hit == 0;) - 这是预期的行为。但是,当函数返回最高层递归时,由于某种原因child_inter.hit被设置为1(但应该设置为0)。

有什么建议吗?

提前谢谢你。

最佳答案

我认为您的问题是由您返回默认初始化的 R3Intersection 引起的(即,当它不相交时您不返回 shape_inter ).根据其默认构造函数,您可能会得到所见即所得。

关于C++ 递归错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2556227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com