eclipse 定义一个二维向量<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-05-05 10:22:16 浏览: 185
以下是一个简单的实现示例:
```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) {
double newX = this.x + other.x;
double newY = this.y + other.y;
return new Vector2D(newX, newY);
}
public Vector2D subtract(Vector2D other) {
double newX = this.x - other.x;
double newY = this.y - other.y;
return new Vector2D(newX, newY);
}
public double dotProduct(Vector2D other) {
return this.x * other.x + this.y * other.y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
@Override
public String toString() {
return "<" + x + ", " + y + ">";
}
}
```
我们可以使用以下代码进行测试:
```java
Vector2D v1 = new Vector2D(1, 2);
Vector2D v2 = new Vector2D(3, 4);
System.out.println("v1 = " + v1);
System.out.println("v2 = " + v2);
Vector2D v3 = v1.add(v2);
System.out.println("v1 + v2 = " + v3);
Vector2D v4 = v1.subtract(v2);
System.out.println("v1 - v2 = " + v4);
double dotProduct = v1.dotProduct(v2);
System.out.println("v1 * v2 = " + dotProduct);
```
输出结果将是:
```
v1 = <1.0, 2.0>
v2 = <3.0, 4.0>
v1 + v2 = <4.0, 6.0>
v1 - v2 = <-2.0, -2.0>
v1 * v2 = 11.0
```
阅读全文