湖南师大acm problem 10384 计算点到线段之间的距离

http://acm.hunnu.edu.cn/online/?action=problem&type=show&id=10834&courseid=52
一开始的时候感觉这道题目很容易,只要用海伦公式一算,不就可以算出结果;但是后来一看,给出的测试数据只有一组是对的,就在找错,在书上一画图,就感觉到可以三点组成的是钝角三角形,不能直接用面积除以底边,因为是到线段的距离而不是到直线的距离;改了之后,数据是通过了,但是提交是WA,所以又在想到底是哪里、出错了,最终是没有考虑到三点共线问题!唉,真是浪费了很多时间!!最后终于通过了!!
下面是AC的C++代码:
#include<cstdio>
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
struct point
{
       double x,y;
};
double distance(double x1,double y1,double x2,double y2)//计算距离;
{
       double l;
       l = sqrt(( x1 - x2) * ( x1 - x2 ) + ( y1 - y2 ) * (y1 - y2 ));
       return l;
}
double Area(double x1,double y1,double x2,double y2,double x3,double y3)//计算面积;
{
        double a,b,c,l,area;
        a = distance(x1,y1,x2,y2);
        b = distance(x2,y2,x3,y3);
        c = distance(x1,y1,x3,y3);
        l = (a + b + c) / 2;
        area = sqrt( l * (l - a ) * ( l - b ) * ( l - c ));//海伦公式计算面积;
        return area;
}


int main()
{
        int t;
        double l,area,x1,y1,x2,y2,s,t1,t2,t3,x3,y3,m,n;
        point a,b,c;
        cin>>t;
        while(t--)
        {
                cin>>a.x>>a.y>>b.x>>b.y>>c.x>>c.y;
                x1 = a.x - b.x; y1 = a.y - b.y;
                x2 = c.x - b.x; y2 = c.y - b.y;
                x3 = a.x - c.x; y3 = a.y - c.y;
                m = x1 * x2 + y1 * y2;//用向量判断夹角
                n = (-1) * (x2 * x3 + y2 * y3);
                t1 = distance(a.x,a.y,b.x,b.y);
                t2 = distance(a.x,a.y,c.x,c.y);
                t3 = distance(b.x,b.y,c.x,c.y);
                if(fabs(x1 * y2 - x2 * y1) < 1e-9 || m * n < 0)//如果三点共线或者是钝角;
                { 
                
                        if(fabs(t1 + t2 - t3) < 1e-9)
                                s = 0;
                        else
                        {
                                if( t1 > t2)
                                    s = t2;
                                else
                                    s = t1;
                        }
                        cout<<setprecision(2)<<fixed<<s<<endl;
                }
                
                else //是锐角的情况;
                {
                        area = Area(a.x,a.y,b.x,b.y,c.x,c.y);
                        l = distance(b.x,b.y,c.x,c.y);
                        cout<<setprecision(2)<<fixed<<2*area/l<<endl;
                }
        }
        return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值