gpt4 book ai didi

c++ - 查找交集时出现浮点异常

转载 作者:行者123 更新时间:2023-11-28 02:06:57 24 4
gpt4 key购买 nike

考虑这段代码:

Point findIntersection(Line l1, Line l2) 
{
int T1, T2;
T2 = (l2.d.x*(l1.p.y-l2.p.y) + l2.d.y*(l2.p.x-l1.p.x))/(l1.d.x*l2.d.y - l1.d.y*l2.d.x);
T1 = (l1.p.x+l1.d.x*T2-l2.p.x)/l2.d.x;
if (T1>0 && 0<T2<1) {
return {l2.p.x+l2.d.x*T1, l2.p.y+l2.d.y*T1};
}
}

(完整代码 http://pastebin.com/M6G40F4M )

此代码在第 3 和 4 行(以及较大代码片段中的第 13 和 14 行)导致浮点异常。我的问题是为什么会发生这种情况,以及找到两条线相交位置的正确方法是什么。我知道这些错误通常在除以零时发生,但我不确定我在哪里做这件事以及如何避免。

最佳答案

你除以零。
让我们来证明一下。

我将在打开警告和未定义行为 sanitizer 的情况下进行编译。

clang++-3.9 -std=c++1z -g -Weverything -fsanitize=undefined  -o main t.cpp

警告:

main.cpp:16:12: warning: generalized initializer lists are incompatible with C++98 [-Wc++98-compat]
return {l2.p.x+l2.d.x*T1, l2.p.y+l2.d.y*T1};
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:10:7: warning: no previous prototype for function 'findIntersection' [-Wmissing-prototypes]
Point findIntersection(Line l1, Line l2)
^
main.cpp:18:1: warning: control may reach end of non-void function [-Wreturn-type]
}
^
main.cpp:22:20: warning: generalized initializer lists are incompatible with C++98 [-Wc++98-compat]
case 0: return {r.p.x, r.d.y};
^~~~~~~~~~~~~~
main.cpp:25:20: warning: generalized initializer lists are incompatible with C++98 [-Wc++98-compat]
case 3: return {r.d.x, r.p.y};
^~~~~~~~~~~~~~
main.cpp:19:7: warning: no previous prototype for function 'getRectPoint' [-Wmissing-prototypes]
Point getRectPoint(Rect r, int n)
^
main.cpp:27:1: warning: control may reach end of non-void function [-Wreturn-type]
}
^

当我们运行它时:

main.cpp:13:57: runtime error: division by zero
[1] 26614 floating point exception (core dumped) ./main

第 13 行:

T2 = (l2.d.x*(l1.p.y-l2.p.y) + l2.d.y*(l2.p.x-l1.p.x))/(l1.d.x*l2.d.y - l1.d.y*l2.d.x);

关于c++ - 查找交集时出现浮点异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37128650/

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