#include<iostream>#include<cmath>
using namespace std;#define EPS (1e-10)#define equals(a, b) (fabs((a) - (b)) < EPS)//实数判断是否为0的方法
class Point//建立point类,里面包含很多point的运算符{
public:double x, y;Point(double x =0,double y =0):x(x),y(y){}//定义point中的特定运算符
Point operator +(Point p){returnPoint(x + p.x, y + p.y);}
Point operator -(Point p){returnPoint(x - p.x, y - p.y);}
Point operator *(double a){returnPoint(a * x, a * y);}
Point operator /(double a){returnPoint(x / a, y / a);}doubleabs(){returnsqrt(norm());}//求每个点的模doublenorm(){return x * x + y * y;}//求出每个点的横坐标平方+纵坐标平方
bool operator <(const Point &p)const{return x != p.x ? x < p.x : y < p.y;}
bool operator ==(const Point &p)const{returnfabs(x - p.x)< EPS &&fabs(y - p.y)< EPS;}};typedef Point Vector;struct Segment
{
Point p1, p2;//一个线段包含两个已知点,一个点又对应一个坐标};doubledot(Vector a, Vector b){return a.x * b.x + a.y * b.y;}doublecross(Vector a, Vector b){return a.x*b.y - a.y*b.x;}//用内积判断正交
bool isOrthogonal(Segment s1, Segment s2){returnequals(dot(s1.p2 - s1.p1, s2.p2 - s2.p1),0.0);}//用外积判断平行
bool isParallel(Segment s1, Segment s2){returnequals(cross(s1.p2 - s1.p1, s2.p2 - s2.p1),0.0);}intmain(){int q;
cin>>q;
Segment s1,s2;while(q--){
cin>>s1.p1.x>>s1.p1.y>>s1.p2.x>>s1.p2.y>>s2.p1.x>>s2.p1.y>>s2.p2.x>>s2.p2.y;if(isOrthogonal(s1,s2)){
cout<<1<<endl;}elseif(isParallel(s1,s2)){
cout<<2<<endl;}else{
cout<<0<<endl;}}}
方法二: 用内积外积判断正交平行时,形参为向量
#include<iostream>#include<cmath>
using namespace std;#define EPS (1e-10)#define equals(a, b) (fabs((a) - (b)) < EPS)
class Point {
public:double x, y;Point(double x =0,double y =0):x(x),y(y){}
Point operator +(Point p){returnPoint(x + p.x, y + p.y);}
Point operator -(Point p){returnPoint(x - p.x, y - p.y);}
Point operator *(double a){returnPoint(a * x, a * y);}
Point operator /(double a){returnPoint(x / a, y / a);}doubleabs(){returnsqrt(norm());}doublenorm(){return x * x + y * y;}
bool operator <(const Point &p)const{return x != p.x ? x < p.x : y < p.y;}
bool operator ==(const Point &p)const{returnfabs(x - p.x)< EPS &&fabs(y - p.y)< EPS;}};typedef Point Vector;doubledot(Vector a, Vector b){return a.x * b.x + a.y * b.y;}doublecross(Vector a, Vector b){return a.x*b.y - a.y*b.x;}//内积判断正交
bool isOrthogonal(Vector a, Vector b){returnequals(dot(a, b),0.0);}//外积判断平行
bool isParallel(Vector a, Vector b){returnequals(cross(a, b),0.0);}intmain(){int q;
cin>>q;
Point p0, p1, p2, p3;while(q--){
cin>>p0.x>>p0.y>>p1.x>>p1.y>>p2.x>>p2.y>>p3.x>>p3.y;if(isOrthogonal(p0-p1, p2-p3)){
cout<<1<<endl;}elseif(isParallel(p0-p1, p2-p3)){
cout<<2<<endl;}else{
cout<<0<<endl;}}}