判断点是否在三角形内

来源:互联网 发布:淘宝爱他美是真是假 编辑:程序博客网 时间:2024/06/04 19:00
假设现有100*100的平面,平面上有三个点组成三角形,现有另外的一个点。请判断该点是否在三角形内部

输入格式:共2行数据,第一行是以空格为分隔符的数组,共6个元素,分别表示三个点的坐标。第二行是
以空格为分隔符的数组,共2个元素,表示另外点的坐标

输出格式:共1行数据,如果在三角形内部(含边线)输出1,反之输出0

样例(1):
输入:
23 27 94 57 64 58 
31 12
输出

0

代码(转)先看看然后我自己再来改改看看

#include <iostream>
#include <stdexcept>
 
// 判断(x, y), (xx, yy)是否在由(x1, y1)和(x2, y2)组成的直线的同一侧
bool on_the_same_side(
    int const x,
    int const y,
    int const xx,
    int const yy,
    int const x1,
    int const y1,
    int const x2,
    int const y2
    ) {
    int const
        dx21 = x2 - x1, dy21 = y2 - y1,
        dx = x - x1, dy = y - y1,
        dxx = xx - x1, dyy = yy - y1,
        tmp = dxx*dy21 - dyy*dx21;
    if (tmp == 0) throw std::invalid_argument("不是三角形");
 
    return
        (dx*dy21 - dy*dx21 >= 0) ==
        (tmp > 0);
}
 
int main() {
    int x1, y1, x2, y2, x3, y3, x, y;
    std::cin >> x1 >> y1
        >> x2 >> y2
        >> x3 >> y3
        >> x >> y;
    try {
        std::cout << (
            on_the_same_side(x, y, x3, y3, x1, y1, x2, y2) &&
            on_the_same_side(x, y, x2, y2, x1, y1, x3, y3) &&
            on_the_same_side(x, y, x1, y1, x2, y2, x3, y3)) << "\n";
    }
    catch (std::exception const &err) {
        std::cerr << err.what() << "\n";
        return __LINE__;
    }
 
    return 0;
}
















原创粉丝点击