C++ 在给定斜率的线上找到给定距离处的点(Find points at a given distance on a line of given slope)

给定二维点 p(x 0 , y 0 )的坐标。找出距离该点为 L 的点,连接这些点所形成的直线的斜率M

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

我们需要找到与给定点距离为 L 的两个点,它们位于斜率为 M 的直线上。
这个想法已在下面的文章中介绍过。 

利用中点求矩形的角:

Javascript 使用中点查找矩形的角:https://blog.youkuaiyun.com/hefeng_aspnet/article/details/149935351
C# 使用中点查找矩形的角:https://blog.youkuaiyun.com/hefeng_aspnet/article/details/149935336
Python 使用中点查找矩形的角:https://blog.youkuaiyun.com/hefeng_aspnet/article/details/149935318
Java 使用中点查找矩形的角:https://blog.youkuaiyun.com/hefeng_aspnet/article/details/149935302
C++ 使用中点查找矩形的角:https://blog.youkuaiyun.com/hefeng_aspnet/article/details/149935238

根据输入斜率,问题可分为 3 类。  

1、如果斜率为零,我们只需要调整源点的 x 坐标
2、如果斜率无限大,则需要调整 y 坐标
3、对于其他斜率值,我们可以使用以下方程来找到点

 

公式英文: 

现在利用上述公式我们可以找到所需的点。

下面是实现:

// C++ program to find the points on a line of
// slope M at distance L
#include <bits/stdc++.h>
using namespace std;

// structure to represent a co-ordinate
// point
struct Point {

    float x, y;
    Point() { x = y = 0; }
    Point(float a, float b) { x = a, y = b; }
};

// Function to print pair of points at
// distance 'l' and having a slope 'm'
// from the source
void printPoints(Point source, float l, int m)
{
    // m is the slope of line, and the
    // required Point lies distance l
    // away from the source Point
    Point a, b;

    // slope is 0
    if (m == 0) {
        a.x = source.x + l;
        a.y = source.y;

        b.x = source.x - l;
        b.y = source.y;
    }

    // if slope is infinite
    else if (m == std::numeric_limits<float>::max()) {
        a.x = source.x;
        a.y = source.y + l;

        b.x = source.x;
        b.y = source.y - l;
    }
    else {
        float dx = (l / sqrt(1 + (m * m)));
        float dy = m * dx;
        a.x = source.x + dx;
        a.y = source.y + dy;
        b.x = source.x - dx;
        b.y = source.y - dy;
    }

    // print the first Point
    cout << a.x << ", " << a.y << endl;

    // print the second Point
    cout << b.x << ", " << b.y << endl;
}

// driver function
int main()
{
    Point p(2, 1), q(1, 0);
    printPoints(p, sqrt(2), 1);
    cout << endl;
    printPoints(q, 5, 0);
    return 0;
}

输出:

3, 2 
1, 0 

6, 0 
-4, 0

时间复杂度: O(1) 

辅助空间: O(1)
 

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hefeng_aspnet

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

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

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

打赏作者

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

抵扣说明:

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

余额充值