面积法实现判断一个点是否在三角形内部

题目描述:

果园里的树排列成矩阵。他们的x和y的坐标均是1~99的整数。输入若干个三角形,依次统计每个三角形内部和边界上共有多少棵树。

输入:

1.5  1.5       1.5  6.8      6.8  1.5

10.7  6.9     8.5  1.5      14.5  1.5

#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;

class Point{
private:
    long double x,y;
public:
    Point();
    void Get(long double m,long double n);
    long double get_x();
    long double get_y();
};

Point::Point()
{
    x = 0;
    y = 0;
}

void Point::Get(long double m, long double n)
{
    this->x = m;
    this->y = n;
}

double long Point::get_x()
{
    return x;
}

long double Point::get_y()
{
    return y;
}

istream& operator >> (istream &in, Point &point)
{
    long double Pos_x,Pos_y;
    in >> Pos_x >> Pos_y;
    //cout << Pos_x << "&&&" << Pos_y << endl;
    point.Get(Pos_x,Pos_y);
    return in;
}

long double Area(Point p1, Point p3, Point p2)
{
    //double edge = sqrt(pow(p1.get_x() - p2.get_x(),2) + pow(p1.get_y() - p2.get_y(),2));
    //cout << "底边为 " << edge << endl;
    //double high = abs( (p2.get_x()- p1.get_x())*p3.get_y() + (p1.get_y()- p2.get_y())*p3.get_x() + ((p2.get_y()- p1.get_y())*p2.get_x() + (p1.get_x()- p2.get_x())*p2.get_y())) / sqrt(pow((p2.get_x()- p1.get_x()),2) + pow((p2.get_y()- p1.get_y()),2));
    //cout << "高为 " << high << endl;
    long double sum = 0;
    if ( (p2.get_x()- p1.get_x()) != 0)
    {
        sum = sqrt(pow(p1.get_x() - p2.get_x(),2) + pow(p1.get_y() - p2.get_y(),2)) * 
        abs( (p2.get_x()- p1.get_x())*p3.get_y() + (p1.get_y()- p2.get_y())*p3.get_x() + ((p2.get_y()- p1.get_y())*p2.get_x() + (p1.get_x()- p2.get_x())*p2.get_y())) / sqrt(pow((p2.get_x()- p1.get_x()),2) + pow((p2.get_y()- p1.get_y()),2));
    }
    else
    {
        sum = abs(p2.get_y() - p1.get_y())*abs(p3.get_x() - p2.get_x());
    }
    
    //cout << "^^^" << sum << endl;
    return sum;
}

int main()
{
    Point P[3];
    for (int i = 0; i < 3; i++)
    {
        cin >> P[i];
        //cout << P[i].get_x() << "***" << P[i].get_y() << endl;
    }
    
    int count = 0;
    for (int i = 1; i < 100; i++)
    {
        for (int j = 1; j < 100; j++)
        {
            Point point;
            point.Get(i,j);
            long double sum1 = 0;
            long double sum2 = 0;
            sum1 = Area(P[0],P[1],point) + Area(P[1],P[2],point) + Area(P[0],P[2],point);
            //cout << "***" << sum1 << endl;
            sum2 = Area(P[0],P[1],P[2]);
            //cout << "&&&" << sum2 << endl;
            if (fabs(sum1-sum2) <= 0.00001)
            {
                //cout << i << "####" << j << endl;
                count++;
            }
        }
    }
    cout << count << endl;

    system("pause");
    return 0;
}



转载于:https://my.oschina.net/u/2286203/blog/368336

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值