用C++将一个xy坐标点往一个输入方向移动标量长度得到另一点
时间: 2024-03-13 14:43:19 浏览: 18
可以使用以下代码实现:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
struct Point {
double x;
double y;
};
// 将点 p 沿向量 v 移动 distance 长度得到新点
Point movePoint(Point p, Point v, double distance) {
double len = sqrt(v.x * v.x + v.y * v.y);
Point unitV = {v.x / len, v.y / len}; // 单位向量
Point newP = {p.x + unitV.x * distance, p.y + unitV.y * distance};
return newP;
}
int main() {
Point p = {1.0, 2.0};
Point v = {3.0, -4.0};
double distance = 5.0;
Point newP = movePoint(p, v, distance);
cout << "(" << newP.x << ", " << newP.y << ")" << endl; // 输出移动后的点
return 0;
}
```
其中,`Point` 结构体表示一个二维坐标点,`movePoint` 函数接收一个点 `p`、一个向量 `v` 和一个标量长度 `distance`,并将点 `p` 沿着向量 `v` 的方向移动 `distance` 的长度得到新点,最后返回新点。在 `main` 函数中,我们定义了一个点 `p`、一个向量 `v` 和一个标量长度 `distance`,然后调用 `movePoint` 函数得到移动后的新点,并将其输出。