0

このコードを検討してください:

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 行目) で浮動小数点例外が発生します。私の質問は、なぜこれが起こるのか、そして2本の線が交差する場所を見つける正しい方法は何でしょうか. これらのエラーは通常、ゼロで除算するときに発生することはわかっていますが、どこでそれを行っているのか、どのように防ぐことができるのかわかりません。

4

1 に答える 1

2

あなたはゼロで割っています。
証明しましょう。

未定義の動作サニタイザーと同様に、警告をオンにしてコンパイルします。

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);
于 2016-05-10T03:31:04.713 に答える