我是C ++的新手。
我在下面编写了这个代码,它应该告诉我2条线是否有交点,所以我想在y = Mx + B方程中两条等于“M”的线不应该相交而其他所有线都会相交。
该程序似乎理解这一点,但除非输入的线段的斜率为0,否则输出inf或-inf。
为什么会这样?
#include <iostream>
using namespace std;
int main ()
{
typedef double vector2d[2];
vector2d pointA, pointB, pointC, pointD;
double LineSeg1, LineSeg2;
double yes, no;
cout << "Enter x for point A: ";
cin >> pointA[0];
cout << "Enter y for point A: ";
cin >> pointA[1];
cout << "Point A = (" << pointA[0] << "," << pointA[1] << ")" << endl;
cout << "Enter x for point B: ";
cin >> pointB[0];
cout << "Enter y for point B: ";
cin >> pointB[1];
cout << "Point B = (" << pointB[0] << "," << pointB[1] << ")" << endl;
cout << "Enter x for point C: ";
cin >> pointC[0];
cout << "Enter y for point C: ";
cin >> pointC[1];
cout << "Point C = (" << pointC[0] << "," << pointC[1] << ")" << endl;
cout << "Enter x for point D: ";
cin >> pointD[0];
cout << "Enter y for point D: ";
cin >> pointD[1];
cout << "Point D = (" << pointD[0] << "," << pointD[1] << ")" << endl;
LineSeg1 = ((pointB[1]-pointA[1])/(pointB[0]-pointB[0]));
cout << "slope segment 1 = (" << LineSeg1 << endl;
LineSeg2 = ((pointD[1]-pointC[1])/(pointD[0]-pointC[0]));
cout << "slope segment 2 = (" << LineSeg2 << endl;
if ( LineSeg1 == LineSeg2 ) {
cout << "no\n";
}
else ( LineSeg1 != LineSeg2 ) ;{
cout << "yes\n";
}
return 0;
}
答案 0 :(得分:1)
这一行:
LineSeg1 = ((pointB[1]-pointA[1])/(pointB[0]-pointB[0]));
有一个零除错误。
我相信这个等式应该是:
LineSeg1 = ((pointB[1]-pointA[1])/(pointB[0]-pointA[0]));