C++:判断两个线段是否相交

该文提供了用C++编程实现判断两条线段是否相交的算法。通过计算向量叉积和比较线段端点坐标来确定交点的存在性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如图所示,本文记录了使用C++代码计算两条线段是否有交点。


图1:

图2:


#include "stdafx.h"
#include "TwoLineSegmentsIntersect.h"
#include<iostream>
#include<algorithm>
using namespace std;

int main()
{
	double x1, y1, x2, y2, x3, y3, x4, y4;
	x1 = 0.0;
	y1 = 0.0;
	x2 = 1.0;
	y2 = 1.0;
	x3 = 0.0;
	y3 = 1.0;
	x4 = 1.0;
	y4 = 0.0;
	double startPointofLine1[2] = { x1, y1 };
	double endPointofLine1[2] = { x2, y2 };
	double startPointofLine2[2] = { x3, y3 };
	double endPointofLine2[2] = { x4, y4 };
	bool result = judgeWhetherLineSegmentsIntersect(startPointofLine1, endPointofLine1, startPointofLine2, endPointofLine2);

	cout << result << endl;

	system("pause");

	return 0;
}

bool judgeWhetherLineSegmentsIntersect(double startPointofLine1[2], double endPointofLine1[2], double startPointofLine2[2], double endPointofLine2[2])
{
	double x1, y1, x2, y2, x3, y3, x4, y4;
	double a, b, c, d;//表示向量叉积
	x1 = startPointofLine1[0];
	y1 = startPointofLine1[1];
	x2 = endPointofLine1[0];
	y2 = endPointofLine1[1];
	x3 = startPointofLine2[0];
	y3 = startPointofLine2[1];
	x4 = endPointofLine2[0];
	y4 = endPointofLine2[1];
	a = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1);//向量AB * AC的叉积
	b = (x2 - x1) * (y4 - y1) - (y2 - y1) * (x4 - x1);//AB * AD
	c = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3);//CD * CA
	d = (x4 - x3) * (y2 - y3) - (y4 - y3) * (x2 - x3);//CD * CB
	if (max(x1, x2) < min(x3, x4) || max(x3, x4) < min(x1, x2)
		|| max(y1, y2) < min(y3, y4) || max(y3, y4) < min(y1, y2))
		return false;
	else if (a * b <= 0 && c * d <= 0)
		return true;
	else
		return false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_养乐多_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值