C++ 定义一个函数,判断三个二维坐标上的点是否在同一条直线上。
#include <iostream>
#include <iomanip>
#include <type_traits>
using namespace std;
template <typename T>
typename enable_if<is_integral<T>::value, bool>::type
iszero(T x) { return x == 0; }
template <typename T>
typename enable_if<is_floating_point<T>::value, bool>::type
iszero(T x) { return abs(x) < 1e-6; }
template <typename T>
bool colinear(const T a[2], const T b[2], const T c[2])
{
T u[2], v[2];
u[0] = b[0] - a[0];
u[1] = b[1] - a[1];
v[0] = c[0] - a[0];
v[1] = c[1] - a[1];
return iszero(u[0] * v[1] - u[1] * v[0]);
}
int main()
{
int a[3][2] = {0, 0, 1, 1, 2, 2};
float b[3][2] = {0, 0, 1, 1, 2, 2};
cout << boolalpha
<< colinear(a[0], a[1], a[2]) << '\n'
<< colinear(b[0], b[1], b[2]) << '\n';
return 0;
}
原理 y= kx+b 判断是否在同一直线;两点确定一条直线,算出k和b,再讲第三点带入方程验证即可。
bool checkThreePointOnALine(POINT P1, POINT P2, POINT P3)
{
double k, b;
k = (P2.y - P1.y) / (P2.x - P1.x);
b = ((P2.y + P1.y) - k * (P2.x - P1.x)) / 2;
if (P3.y == k * P3.x + b)
return true;
else
return false;
}
int main()
{
POINT p1, p2, p3;
p1.x = 0;
p1.y = 0;
p2.x = 5;
p2.y = 5;
p3.x = 10;
p3.y = 10;
bool onLine = checkThreePointOnALine(p1,p2,p3);
if(onLine)
cout << "三点在同一直线" << endl;
else
cout << "三点不在同一直线" << endl;
return 0;
}