查找交集时出现浮点异常
floating point exception when finding intersection
考虑这个代码:
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)。我的问题是为什么会发生这种情况,以及找到两条线相交的正确方法是什么。我知道这些错误通常发生在除以零的时候,但我不确定我在哪里这样做,以及如何防止它。
您正在除以零
让我们证明一下。
我将编译带有警告的,以及一个未定义的行为净化程序。
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);
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 在C++中查找文件
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 模板元程序查找相似的连续类型名称
- 在UNIX系统中使用DIR查找文件的字节大小
- 查找最接近的大于当前数字的数字的索引
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 查找后更改类变量
- 使用正则表达式regex_search在字符串中查找字符串
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 使用用户定义的函数查找完美数时出现浮点异常错误
- 如何在 VS C++ 中查找发生异常的位置
- 查找哪个函数在 VC++6 中引发异常
- 查找交集时出现浮点异常
- std::string异常以及如何查找已编译的c++应用程序的平台工具集
- 模板 ID 中的好友查找异常