用c++实现一个二维向量
时间: 2023-08-24 20:07:17 浏览: 53
当然,下面是用 C++ 实现的一个简单的二维向量类(Vector2D)的示例代码:
```cpp
#include <iostream>
#include <cmath>
class Vector2D {
public:
double x, y;
Vector2D(double x_val, double y_val) : x(x_val), y(y_val) {}
Vector2D operator+(const Vector2D& other) const {
return Vector2D(x + other.x, y + other.y);
}
Vector2D operator-(const Vector2D& other) const {
return Vector2D(x - other.x, y - other.y);
}
Vector2D operator*(double scalar) const {
return Vector2D(x * scalar, y * scalar);
}
double magnitude() const {
return std::sqrt(x * x + y * y);
}
Vector2D normalize() const {
double mag = magnitude();
return Vector2D(x / mag, y / mag);
}
};
int main() {
// 创建向量
Vector2D v1(2.0, 3.0);
Vector2D v2(-1.0, 4.0);
// 向量加法
Vector2D v3 = v1 + v2;
std::cout << "(" << v3.x << ", " << v3.y << ")" << std::endl;
// 向量减法
Vector2D v4 = v1 - v2;
std::cout << "(" << v4.x << ", " << v4.y << ")" << std::endl;
// 向量乘法
Vector2D v5 = v1 * 2.0;
std::cout << "(" << v5.x << ", " << v5.y << ")" << std::endl;
// 计算向量的模
double mag = v1.magnitude();
std::cout << mag << std::endl;
// 计算单位向量
Vector2D v6 = v1.normalize();
std::cout << "(" << v6.x << ", " << v6.y << ")" << std::endl;
return 0;
}
```
这个示例演示了如何创建二维向量,进行向量的加法、减法、乘法,以及计算向量的模和单位向量。希望对你有帮助!如果有任何问题,请随时提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)