《Cracking the Coding Interview》——第7章:数学和概率论——题目3

2014-03-20 02:05

题目:给定笛卡尔二维平面上两条直线,判断它们是否相交。

解法:相交、重合、平行。

代码:

 1 // 7.3 Given two lines on the Cartesian, determine if they would intersect.

 2 #include <cstdio>

 3 using namespace std;

 4 

 5 int main()

 6 {

 7     // a * x + b * y + c = 0;

 8     // d * x + e * y + f = 0;

 9     int a, b, c, d, e, f;

10     bool suc;

11     

12     while (scanf("%d%d%d%d%d%d", &a, &b, &c, &d, &e, &f) == 6) {

13         if ((a == 0 && b == 0) || (d == 0 && e == 0)) {

14             // invalid line

15             suc = false;

16         } else if (a * e == b * d) {

17             if (a * f == c *d) {

18                 // coincident

19                 suc = true;

20             } else {

21                 // parallel

22                 suc = false;

23             }

24         } else {

25             // intersect

26             suc = true;

27         }

28         if (suc) {

29             printf("Yes\n");

30         } else {

31             printf("No\n");

32         }

33     }

34     

35     return 0;

36 }

 

你可能感兴趣的:(interview)