判断点是否在三角形内

假设现有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;
}
















### 面积法判断是否三角形内的C++代码实现 以下是使用面积法判断是否三角形内的C++代码示例。该方法通过计算三角形的总面积以及由测试三角形构成的三个子三角形的面积,来判断测试是否位于三角形内部。 ```cpp #include <iostream> #include <cmath> using namespace std; // 计算三角形面积的函数 float area(int x1, int y1, int x2, int y2, int x3, int y3) { return abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } // 判断是否三角形内 bool isInside(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y) { // 计算三角形ABC的总面积 float A = area(x1, y1, x2, y2, x3, y3); // 计算三角形PBC的面积 float A1 = area(x, y, x2, y2, x3, y3); // 计算三角形PAC的面积 float A2 = area(x1, y1, x, y, x3, y3); // 计算三角形PAB的面积 float A3 = area(x1, y1, x2, y2, x, y); // 如果总面积等于三个子三角形面积之和,则三角形内 if (A == A1 + A2 + A3) return true; else return false; } int main() { // 定义三角形的三个顶坐标 int x1 = 0, y1 = 0; int x2 = 20, y2 = 0; int x3 = 10, y3 = 30; // 定义测试坐标 int x = 10, y = 15; // 判断测试是否三角形内 if (isInside(x1, y1, x2, y2, x3, y3, x, y)) cout << "Inside"; else cout << "Not Inside"; return 0; } ``` 上述代码中,`area` 函数用于计算三角形的面积[^3],而 `isInside` 函数则根据面积法判断是否位于三角形内部。如果测试三角形构成的三个子三角形面积之和等于原三角形的总面积,则测试位于三角形内部[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值