如何找到 2 条线段之间的交点坐标 C++.

how can i find the coordinates of intersection between 2 line segments C++

本文关键字:之间 C++ 坐标 何找 段之间      更新时间:2023-10-16

我对 C++ 编程语言很陌生,我只需要知道如何在给定起点和终点的情况下声明一组线段? C++有这样的事情吗?我有这段代码,它从文本文件中读取线段的起点和终点,并将输入分为 4 个向量:X_start、Y_start、X_end、Y_end。我需要知道如何使用这些向量来定义线段?任何帮助将不胜感激。提前致谢

#include <iostream>
#include <algorithm> // for std::copy#include <iostream>
#include <iterator>
#include <fstream>
#include <math.h>
#include <vector>
#include <algorithm> // for std::copy
using namespace std;
int main()
{
std::ifstream is("D:\Task1.txt");
std::istream_iterator<double> start(is), end;
std::vector<double> numbers(start, end);
std::vector<double> X_start(start, end);
std::vector<double> Y_start(start, end);
std::vector<double> X_end(start, end);
std::vector<double> Y_end(start, end);
std::vector<double>::iterator i;
std::vector<double>::iterator j;
float left, top, right, bottom; // Bounding Box For Line Segments
left = 12;
top = 12;
right = 0;
bottom = 0;
std::cout << "Read " << numbers.size() << " numbers" << std::endl;
std::copy(numbers.begin(), numbers.end(), 
        std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
for (vector<double>::iterator i = numbers.begin();
                       i != numbers.end();
                       ++i)
{
for(int j = 0; j < numbers.size(); j = j+4)
{
std::cout << "elemnts of X_start " << numbers[j] << "  " <<std::endl;
X_start.push_back(numbers[j]);
}
for(int k = 1; k < numbers.size(); k = k+4)
{
std::cout << "elemnts of Y_start " << numbers[k] << " " <<std::endl;
Y_start.push_back(numbers[k]);
}
for(int l = 2; l < numbers.size(); l = l+4)
{
std::cout << "elemnts of X_end " << numbers[l] << " " <<std::endl;
X_end.push_back(numbers[l]);
}
for(int m = 3; m < numbers.size(); m = m+4)
{
std::cout << "elemnts of Y_end " << numbers[m] << " " <<std::endl;
Y_end.push_back(numbers[m]);
}
getchar();
}   
}

"我对 c++ 编程语言很陌生"

C++有多新?你了解你首先要做的事情所涉及的数学吗?

我使用以下函数。只需修改它即可满足您的要求。

class Point
{
    public:
    float x,y;
};

class LineSegment
{
    public:
    Point top;
    Point bottom;
};
Point* getIntersectionPoint(LineSegment line1,LineSegment line2)
{
    float s1_x, s1_y, s2_x, s2_y;
    float p1_x = line1.bottom.x,p1_y = line1.bottom.y;
    float p0_x = line1.top.x,p0_y = line1.top.y;
    float p3_x = line2.bottom.x,p3_y = line2.bottom.y;
    float p2_x = line2.top.x,p2_y = line2.top.y;
    s1_x = p1_x - p0_x;     s1_y = p1_y - p0_y;
    s2_x = p3_x - p2_x;     s2_y = p3_y - p2_y;
    float s, t;
    s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y);
    t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);
    if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
    {
        Point *intsPoint = (Point *)malloc(sizeof(Point));
        intsPoint->x = p0_x + (t * s1_x);
        intsPoint->y = p0_y + (t * s1_y);
        return intsPoint;
    }
    return NULL;
}