我相信哪怕一点光,也能驱散学习中的迷雾,我在这分享一点自己的挫见
思路:
这题最大的难点就是abc三个常数要怎么去构造,这里需要数学公式去推导,虽然是初中水平,也能体现编程和数学密不可分了。因为我之后要涉及ai算法,需要线代和高数的知识去研究像傅里叶滤波算法,矩阵运算等等知识,所以苦逼的自学日子又要开始了。
整体思路就是构造点和线对象,线是由始点终点所构成,由两点可以得出一条线段。
直线方程:Ax+By+C = 0
只要能知道一条线段的abc参数,便可以计算两条线的交点。
公式推导:
详细代码
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
class Line;//Point类需要Line的类型,所以需要先申明。
class Point {
public:
Point(double x = 0,double y = 0):x(x),y(y) {}
Point(const Point& p) :x(p.x), y(p.y) {}
~Point() {}
Point setPoint(Line& l1, Line& l2);
public:
double x,y;
};
class Line :public Point{
friend Point Point::setPoint(Line& l1, Line& l2);
//通过命名空间来把函数从Point转到Line,之前函数未定义是因为没有放作用域分辨符
public:
Line GetLine(Point Source, Point Destination);
double LineA() { return a; }//三个参数的传参
double LineB() { return b; }
double LineC() { return c; }//由于不知道没有c时候的x,y对应方程只好把c写出来,
void Show(Point p);
private:
double a, b, c;
};
Point Point::setPoint(Line& l1, Line& l2) {
//Point Point::setPoint,第一个Point是函数返回类型,第二个Point是函数的作用域。
Point ptemp;
double Equational;
Equational = l1.LineA() * l2.LineB() - l2.LineA() * l1.LineB();//因为在类外不能访问私有成员,用函数接口调用私有成员。
//Equational是方程式的意思,这里通过数学计算算出a,b,c常数关于x,y的关系。
ptemp.x = (l1.LineB() * l2.LineC() - l2.LineB() * l1.LineC()) / Equational;
ptemp.y = (l1.LineC() * l2.LineA() - l2.LineC() * l1.LineA()) / Equational;
return ptemp;//把点对象返回。则返回ptemp.x和ptemp.y。
}
Line Line:: GetLine(Point Source, Point Destination) {
//计算直线的方程,main函数里面给出始点和终点
Line ltemp;//给一个Line对象,让这个对象的三个参数分别被给出的两点修饰。
//数学推导a,b,c的方程。
ltemp.a = Source.y - Destination.y;
ltemp.b = Destination.x - Source.x;
ltemp.c = Source.x*Destination.y - Destination.x*Source.y;
return ltemp;
}
void Line::Show(Point p) {//点对象传参
cout << "(" << p.x << "," << p.y << ")" << endl;
}
int main() {
Line l;
double x0, x1, x2, x3, y0, y1, y2, y3;
while (1) {
cout << "直线A的起点到终点:";
cin >> x0 >> y0 >> x1 >> y1;
cout << "直线B的起点到终点:";
cin >> x2 >> y2 >> x3 >> y3;
Line a = l.GetLine(Point(x0, y0), Point(x1, y1));
Line b = l.GetLine(Point(x2, y2), Point(x3, y3));
cout << "两直线交点坐标为:";
l.Show(l.setPoint(a, b));
}
}