2016-06-01 18 views
0

Ich bin sehr neu bei C++.inf output computing line Steigungen

Ich schrieb diesen Code unten, der mir sagen soll, ob 2 Linien einen Schnittpunkt haben, so dachte ich, zwei Linien mit gleichen "M" in der y = Mx + B-Gleichung sollten nicht schneiden und alle anderen würden.

Das Programm scheint dies zu verstehen, aber wenn die Steigung des eingegebenen Liniensegments nicht 0 ist, gibt es inf oder -inf aus.

Warum passiert das?

#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

'pointB [0] -pointB [0]' 'sollte pointB [0] -pointA [0]'. Aber Sie müssen immer noch nach Division durch 0 prüfen. –

+0

Haben Sie zwei Vektoren v0 = A bis B und v1 = C bis D. Wenn dann das Vektorprodukt (Kreuzprodukt) v0 x v1 Null ist, schneiden sich die Linien nicht. –

Antwort

1

diese Zeile:

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

hat eine Division durch Null-Fehler.

Ich glaube, die Gleichung sein sollte:

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

@TStro Wenn dies Ihr Problem behebt, vergessen Sie nicht, die beantwortete Frage zu markieren. – Stephen

+0

Das behebt nicht die Fälle 'pointB [0] == pointA [0]' und 'pointD [0] == pointC [0]' –