计算两条直线的交点--C语言

呵呵,有点急。。。

#include < stdio.h >

typedef 
struct  point{
    
int  x;
    
int  y;
}point;

typedef 
struct  line{
    point point1;
    point point2;
}line;

// 计算两条直线的交点
point getCross(line line1, line line2)
{
    point CrossP;
    
// y = a * x + b;
     int  a1  =  (line1.point1.y  -  line1.point2.y)  /  (line1.point1.x  -  line1.point2.x);
    
int  b1  =  line1.point1.y  -  a1  *  (line1.point1.x);

    
int  a2  =  (line2.point1.y  -  line2.point2.y)  /  (line2.point1.x  -  line2.point2.x);
    
int  b2  =  line2.point1.y  -  a1  *  (line2.point1.x);

    CrossP.x 
=  (b1  -  b2)  /  (a2  -  a1);
    CrossP.y 
=  a1  *  CrossP.x  +  b1;
    
return  CrossP;
}

void  main()
{
    line line1;
    line line2;

    
// line1
    line1.point1.x  =   10 ;
    line1.point1.y 
=   10 ;
    line1.point2.x 
=   50 ;
    line1.point2.y 
=   50 ;

    
// line2
    line2.point1.x  =   2 ;
    line2.point1.y 
=   60 ;
    line2.point2.x 
=   60 ;
    line2.point2.y 
=   0 ;

    point CointP 
=  getCross(line1, line2);
    printf(
" %d,%d\n " , CointP.x, CointP.y);

}

 

转载于:https://www.cnblogs.com/liulei/archive/2010/06/12/1756909.html

三维空间中,直线和平面的交点计算通常涉及到线性代数的概念。在C语言中,你可以使用向量和矩阵运算来求解。以下是一个简单的示例,假设我们有一个通过两个三维点P1(x1, y1, z1)和P2(x2, y2, z2)的直线,以及一个由法向量n(xn, yn, zn)定义的平面。 ```c #include <stdio.h> #include <math.h> // 点结构体 typedef struct { double x; double y; double z; } Point; // 向量结构体 typedef struct { double x; double y; double z; } Vector; // 计算两条线段之间的距离 double distance(Vector v1, Vector v2) { return sqrt(pow(v1.x - v2.x, 2) + pow(v1.y - v2.y, 2) + pow(v1.z - v2.z, 2)); } // 检查直线和平面是否相交 int line_plane_intersection(Point P1, Point P2, Vector n, Point planePt) { Vector direction = {P2.x - P1.x, P2.y - P1.y, P2.z - P1.z}; // 平行于平面的向量,其方向与法向量垂直 Vector parallel_vec = {n.y * direction.z - n.z * direction.y, n.z * direction.x - n.x * direction.z, n.x * direction.y - n.y * direction.x}; // 如果平行向量模长为0,表示直线在平面上,无交点 if (fabs(parallel_vec.x) < DBL_EPSILON && fabs(parallel_vec.y) < DBL_EPSILON && fabs(parallel_vec.z) < DBL_EPSILON) return 0; double t = ((planePt.x - P1.x) * n.x + (planePt.y - P1.y) * n.y + (planePt.z - P1.z) * n.z) / dot(direction, n); // 确保t在0到线段长度之间 if (t > 1 || t < 0) return 0; Point intersection = {P1.x + t * direction.x, P1.y + t * direction.y, P1.z + t * direction.z}; return 1; } int main() { // 例子中的参数 Point P1 = {0, 0, 0}, P2 = {1, 1, 1}; Vector n = {1, 0, 0}; // 假设平面的法向量是x轴正方向 Point planePt = {0, 0, 0}; // 假设平面经过原点 int result = line_plane_intersection(P1, P2, n, planePt); if (result) printf("直线和平面相交于点: (%f, %f, %f)\n", intersection.x, intersection.y, intersection.z); else printf("直线和平面不相交\n"); return 0; } ``` 这个示例只是一个基础版本,实际应用中可能需要考虑更复杂的情况,比如法向量的方向不确定,或者是处理无穷远的直线等。注意,这里的计算依赖于浮点数精度,可能会有微小误差。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值