INF输出计算线斜率

inf output computing line slopes

本文关键字:斜率 计算 输出 INF      更新时间:2023-10-16

我对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 << "non";
}
else ( LineSeg1 != LineSeg2 ) ;{
    cout << "yesn";
}
return 0;
}

这一行:

LineSeg1 = ((pointB[1]-pointA[1])/(pointB[0]-pointB[0]));

有除以零误差。

我认为等式应该是:

LineSeg1 = ((pointB[1]-pointA[1])/(pointB[0]-pointA[0]));