java 定义一个二维向量<a,b>类,其中a、b为其属性,主要操作如下: 向量相加:<a,b>+<c,d>=<a+c,b+d> 向量相减:<a,b>-<c,d>=<a-c,b-d> 向量内积:<a,b>*<c,d>=a*c+b*d 编程定义该类,并使用该类
时间: 2024-04-30 19:21:15 浏览: 191
二维向量运算
以下是 Java 代码实现:
```java
public class Vector2D {
private double x;
private double y;
public Vector2D(double x, double y) {
this.x = x;
this.y = y;
}
public Vector2D add(Vector2D other) {
return new Vector2D(this.x + other.x, this.y + other.y);
}
public Vector2D subtract(Vector2D other) {
return new Vector2D(this.x - other.x, this.y - other.y);
}
public double dotProduct(Vector2D other) {
return this.x * other.x + this.y * other.y;
}
public void print() {
System.out.println("(" + this.x + ", " + this.y + ")");
}
}
```
可在 `main` 函数中进行测试:
```java
public static void main(String[] args) {
Vector2D v1 = new Vector2D(1, 2);
Vector2D v2 = new Vector2D(3, 4);
Vector2D v3 = v1.add(v2);
v3.print(); // 输出 (4.0, 6.0)
Vector2D v4 = v1.subtract(v2);
v4.print(); // 输出 (-2.0, -2.0)
double dotProduct = v1.dotProduct(v2);
System.out.println(dotProduct); // 输出 11.0
}
```
阅读全文