判断点B是否在线段AC上?

12 篇文章 0 订阅

问题

判断点B是否在线段AC上?

解决方法

1).使用矩阵的秩解决

 矩阵的秩代码

#include <iostream>
#include <vector>
#include <cmath>

class Matrix {
public:
    std::vector<std::vector<double>> data;
    int rows, cols;

    Matrix(int r, int c) : rows(r), cols(c), data(r, std::vector<double>(c, 0)) {}

    // 设置矩阵元素
    void set(int r, int c, double val) {
        if (r >= 0 && r < rows && c >= 0 && c < cols) {
            data[r][c] = val;
        }
    }

    // 获取矩阵元素
    double get(int r, int c) const {
        if (r >= 0 && r < rows && c >= 0 && c < cols) {
            return data[r][c];
        }
        return 0;
    }

    // 打印矩阵
    void print() const {
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                std::cout << data[i][j] << " ";
            }
            std::cout << std::endl;
        }
    }

    // 求矩阵的秩
    int rank() const {
        Matrix temp(*this); // 创建一个临时矩阵,‌用于高斯消元
        int rank = 0;

        for (int col = 0; col < cols; ++col) {
            // 查找当前列中绝对值最大的元素,‌并进行行交换
            int maxRow = rank;
            for (int row = rank + 1; row < rows; ++row) {
                if (std::abs(temp.data[row][col]) > std::abs(temp.data[maxRow][col])) {
                    maxRow = row;
                }
            }

            // 如果当前列的最大元素为0,‌则跳过这一列
            if (temp.data[maxRow][col] == 0) {
                continue;
            }

            // 交换当前列的最大元素所在的行与当前处理的行
            if (maxRow != rank) {
                for (int k = col; k < cols; ++k) {
                    std::swap(temp.data[rank][k], temp.data[maxRow][k]);
                }
            }

            // 将当前列下方的元素消为0
            for (int row = rank + 1; row < rows; ++row) {
                double factor = temp.data[row][col] / temp.data[rank][col];
                for (int k = col; k < cols; ++k) {
                    temp.data[row][k] -= factor * temp.data[rank][k];
                }
            }

            ++rank; // 增加秩
        }

        return rank;
    }
};

int main() {
    Matrix m(3, 3);
    m.set(0, 0, 1);
    m.set(0, 1, 2);
    m.set(0, 2, 3);
    m.set(1, 0, 4);
    m.set(1, 1, 5);
    m.set(1, 2, 6);
    m.set(2, 0, 7);
    m.set(2, 1, 8);
    m.set(2, 2, 9);

    std::cout << "Matrix:" << std::endl;
    m.print();

    std::cout << "Rank: " << m.rank() << std::endl;

    return 0;
}

2).使用向量的点积判断

向量点积代码

// 计算两个向量的点积
float dot(const Vector3D& other) const {
        return x * other.x + y * other.y + z * other.z;
    }

向量长度代码

// 计算向量的长度
    float length() const {
        return sqrt(x * x + y * y + z * z);
    }

结论

使用工具解决问题。两种方法:1.矩阵的秩2.点积。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值