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-05-08 10:22:18 浏览: 12
以下是Java代码实现:
```java
public class Vector2D {
private double a;
private double b;
public Vector2D(double a, double b) {
this.a = a;
this.b = b;
}
public Vector2D add(Vector2D other) {
double newA = this.a + other.a;
double newB = this.b + other.b;
return new Vector2D(newA, newB);
}
public Vector2D subtract(Vector2D other) {
double newA = this.a - other.a;
double newB = this.b - other.b;
return new Vector2D(newA, newB);
}
public double dotProduct(Vector2D other) {
double product = this.a * other.a + this.b * other.b;
return product;
}
}
```
示例使用:
```java
Vector2D v1 = new Vector2D(1, 2);
Vector2D v2 = new Vector2D(3, 4);
Vector2D v3 = v1.add(v2);
System.out.println(v3.a + "," + v3.b); // 输出 "4.0,6.0"
Vector2D v4 = v1.subtract(v2);
System.out.println(v4.a + "," + v4.b); // 输出 "-2.0,-2.0"
double dotProduct = v1.dotProduct(v2);
System.out.println(dotProduct); // 输出 "11.0"
```
以上代码实现了二维向量的加减和内积操作,并且演示了如何使用该类进行向量计算。