点线计算


此页面通过工具从 csdn 导出,格式可能有问题。

#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
struct Point{
    double x,y;
    Point(){};
    Point(double a,double b):x(a),y(b){}
    friend Point operator + (Point a,Point b){
        return Point(a.x+b.x,a.y+b.y);
    }
    friend Point operator - (Point a,Point b){
        return Point(a.x-b.x,a.y-b.y);
    }
    friend Point operator * (Point a,double b){
        return Point(a.x*b,a.y*b);
    }
    friend Point operator / (Point a,double b){
        return Point(a.x/b,a.y/b);
    }
    void input(){
        scanf("%lf%lf",&x,&y);
    }
};
struct line{
    Point a,b;
    line(Point x,Point y):a(x),b(y){}
};
// 点积
double dot(Point a,Point b){
    return a.x*b.x+a.y*b.y;
}
// 叉积
double det(Point a,Point b){
    return a.x*b.y-a.y*b.x;
}
// 判断符号
int aps(double x){
    double eps = 1e-8;
    if (fabs(x)<=eps) return 0;
    if (x>0) return 1;
    return -1;
}
// 有交点
bool isCom(line a,line b){
    return (bool)aps(det(a.a-a.b,b.a-b.b));
}
// 同线
bool isOne(line a,line b){
    if (!aps(det(a.b-a.a,b.a-a.a)) && !(aps(det(a.b-a.a,b.b-a.a)))) return 1;
    return 0;
}
// 求交点
Point crossPoint(line a,line b){
    double s1=det(a.a-b.a,b.b-b.a);
    double s2=det(a.b-b.a,b.b-b.a);
    return (a.a*s2-a.b*s1)/(s2-s1);
}

调用

int main(){
    int n;
    Point c[8];
    scanf("%d",&n);
    printf("INTERSECTING LINES OUTPUT\n");
    while (n--){
        for (int i(1);i<=4;i++){
            c[i].input();
            //printf(" %.2lf %.2lf\n",c[i].x,c[i].y);
        }
        line a = line(c[1],c[2]);
        line b = line(c[3],c[4]);
        if (isOne(a,b)) printf("LINE\n");
            else if (!isCom(a,b)) printf("NONE\n");
                else {
                    Point t=crossPoint(a,b);
                    printf("POINT %.2f %.2f\n",t.x,t.y);    // PS:在G++里,double以%lf读入以%f输出
                }
    }
    printf("END OF OUTPUT\n");
    return 0;
}



Avatar
huiren
Code Artisan

问渠那得清如许,为有源头活水来

下一页
上一页
comments powered by Disqus