设计一个三维向量类,并实现向量的加法、减法以及向量与标量的乘法和除法。
时间: 2024-06-21 19:04:01 浏览: 13
设计一个三维向量类(通常在编程中称为`Vector3D`或`Vector`),首先我们需要定义类的基本属性,包括三个分量(x, y, z),然后实现向量运算的方法。以下是一个简单的Python实现:
```python
class Vector3D:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
# 向量加法
def add(self, other):
return Vector3D(self.x + other.x, self.y + other.y, self.z + other.z)
# 向量减法
def subtract(self, other):
return Vector3D(self.x - other.x, self.y - other.y, self.z - other.z)
# 向量与标量乘法
def multiply(self, scalar):
return Vector3D(self.x * scalar, self.y * scalar, self.z * scalar)
# 向量除以标量,假设标量不为零
def divide(self, scalar):
if scalar != 0:
return Vector3D(self.x / scalar, self.y / scalar, self.z / scalar)
else:
raise ValueError("Cannot divide by zero")
# 示例
vector_a = Vector3D(1, 2, 3)
vector_b = Vector3D(4, 5, 6)
# 加法
vector_sum = vector_a.add(vector_b)
print("加法: ", vector_sum.x, vector_sum.y, vector_sum.z)
# 减法
vector_difference = vector_a.subtract(vector_b)
print("减法: ", vector_difference.x, vector_difference.y, vector_difference.z)
# 乘法和除法
scalar = 2
scaled_vector = vector_a.multiply(scalar)
print("乘法: ", scaled_vector.x, scaled_vector.y, scaled_vector.z)
try:
divided_vector = vector_a.divide(scalar)
except ValueError as e:
print(e)
```
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)