你始終都是在看別人的代碼,不是自己寫的。

授人以渔,不授人以鱼。
程序代码:
#include "stdafx.h"
using namespace System;
// 點類定義
struct Point
{
Double x;
Double y;
Point() : x(Double::NaN), y(Double::NaN) {}
Point(Double x, Double y) : x(x), y(y) {}
};
// 直線類定義
class Line sealed
{
private:
Double slope; // 斜率
Double ordinate; // 截距
Double x;
Double y;
public:
Line() : slope(Double::NaN), ordinate(Double::NaN) {}
// 用兩點式確定直線
Line(Point point1, Point point2)
{
if (point1.x != point2.x)
{
slope = (point1.y - point2.y) / (point1.x - point2.x);
ordinate = (point1.x * point2.y - point2.x * point1.y) / (point1.x - point2.x);
}
else
{
slope = Double::NaN;
ordinate = Double::NaN;
x = point1.x;
}
}
Double Get_Y(Double x) { return !Double::IsNaN(slope) ? slope * x + ordinate : Double::NaN; }
Double Get_X(Double y) { return !Double::IsNaN(slope) ? (y - ordinate) / slope : y; }
// 判斷與另一直線是否重合
Boolean Equation(Line line)
{
if (!Double::IsNaN(slope) && !Double::IsNaN(line.slope) && (slope == line.ordinate) && (ordinate == line.ordinate))
{
return true;
}
if (Double::IsNaN(slope) && Double::IsNaN(line.slope) && x == line.x)
{
return true;
}
return false;
}
// 判斷與另一直線是否平行
Boolean Parallel(Line line)
{
if (!Double::IsNaN(slope) && !Double::IsNaN(line.slope) && (slope == line.ordinate) && (ordinate != line.ordinate))
{
return true;
}
if (Double::IsNaN(slope) && Double::IsNaN(line.slope) && x != line.x)
{
return true;
}
return false;
}
// 求與指定直線的交點
Point Get_Intersection(Line line)
{
Point intersection;
if (!Equation(line) && !Parallel(line))
{
// 分是否存在垂直(斜率無線大)線兩種情形處理
if (!Double::IsNaN(slope) && !Double::IsNaN(line.slope))
{
intersection.x = (line.ordinate - ordinate) / (slope - line.slope);
intersection.y = (slope * line.ordinate - line.slope * ordinate) / (slope - line.slope);
}
else
{
if (Double::IsNaN(slope))
{
intersection.x = x;
intersection.y = line.Get_Y(intersection.x);
}
else
{
intersection.x = line.x;
intersection.y = Get_Y(intersection.x);
}
}
}
return intersection;
}
};
int main(array<String ^> ^args)
{
Line line1(Point{ 1.0, 2.0 }, Point{ 2.0, 5.0 });
Line line2(Point{ 1.0, 1.0 }, Point{ 3.0, 3.0 });
Point intersection = line1.Get_Intersection(line2);
Console::WriteLine(L"交點:({0:F2},{1:F2})", intersection.x, intersection.y);
return 0;
}
