首页 > 其他 > 详细

定义点类和直线类,计算两条直线的交点

时间:2020-01-11 16:19:18      阅读:134      评论:0      收藏:0      [点我收藏+]

定义点类和直线类,计算两条直线的交点。

要求利用 Point 的组合完成 class Line ,也就是说需要利用两个点构成一条直线;

其次题目保证两直线必定相交,也就是说我们直接利用公式求解即可;

代码如下:

技术分享图片
 1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 class Point
 6 {
 7     private:
 8         double x , y;
 9     public:
10         Point(double x_ = 0, double y_ = 0):x(x_),y(y_) {}
11         Point(const Point & rhs);
12         ~Point();
13         Point & operator = (const Point & rhs);
14         friend ostream & operator <<(ostream & os , const Point & rhs);
15         friend class Line;
16 };
17 
18 Point::Point(const Point & rhs)
19 {
20     if(this != &rhs)
21     {
22         x = rhs.x;
23         y = rhs.y;
24     }
25 }
26 
27 Point::~Point()
28 {
29     cout<<"~ ~ ~Point X , Y "<<x<<" , "<<y<<endl;
30 }
31 
32 Point & Point::operator = (const Point & rhs)
33 {
34     x = rhs.x; 
35     y = rhs.y; 
36     return (*this);
37 } 
38 
39 ostream & operator <<(ostream & os , const Point & rhs)
40 {
41     os<<"("<<rhs.x<<" , "<<rhs.y<<")"<<endl;
42     return (os);
43 }
44 
45 class Line
46 {
47     private:
48         Point point0 , point1 ;
49     public:
50         Line(double x0 = 0,double y0 = 0,double x1 = 0,double y1 = 0):point0(x0,y0),point1(x1,y1) { }
51         Line(const Line & rhs);
52         ~Line();
53         Point Jiaodian(const Line zhi1);
54 };
55 
56 Line::Line(const Line & rhs)
57 {
58     if(this != &rhs)
59     {
60         point0 = rhs.point0;
61         point1 = rhs.point1;
62     }
63 }
64 
65 Line::~Line() 
66 {
67     cout<<"~ ~ ~Line Point0 , Point1"<<endl;
68 }
69 
70 Point Line::Jiaodian( const Line zhi1)
71 {
72     double a0,a1,b0,b1,c0,c1;
73     double xx , yy ;
74     a0 = point1.x - point0.x;
75     b0 = point1.y - point0.y;
76     c0 = point0.y*point1.x - point1.y*point0.x;
77     a1 = zhi1.point1.x - zhi1.point0.x;
78     b1 = zhi1.point1.y - zhi1.point0.y;
79     c1 = zhi1.point0.y*zhi1.point1.x - zhi1.point1.y*zhi1.point0.x;
80     xx = (c1*a0 - c0*a1)/(b0*a1 - a0*b1);
81     yy = (c0*b1 - c1*b0)/(a0*b1 - a1*b0);
82     return   Point(xx , yy);
83 }
84 
85 int main()
86 {  
87     int a,b,c,d;
88     cin>>a>>b>>c>>d; 
89     Line L1(a,b,c,d) ;
90     cin>>a>>b>>c>>d;
91     Line L2(a,b,c,d) ;
92     Point aa = L1.Jiaodian(L2); 
93     cout<<"交点为 :"<<aa;
94     return 0;
95 }
View Code

 

测试例子:

0 0 2 2

0 2 2 0

输出:

~ ~ ~Line Point0 , Point1

~ ~ ~Point X , Y 2 , 0

~ ~ ~Point X , Y 0 , 2

交点为 :(1 , 1)

~ ~ ~Point X , Y 1 , 1

~ ~ ~Line Point0 , Point1

~ ~ ~Point X , Y 2 , 0

~ ~ ~Point X , Y 0 , 2

~ ~ ~Line Point0 , Point1

~ ~ ~Point X , Y 2 , 2

~ ~ ~Point X , Y 0 , 0

定义点类和直线类,计算两条直线的交点

原文:https://www.cnblogs.com/2015-16/p/12179992.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!