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 20:22:16 浏览: 17
以下是一个简单的实现示例:
```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
```
相关推荐
![xsd](https://img-home.csdnimg.cn/images/20210720083646.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)
HTTP/1.1 401 Unauthorized WWW-Authenticate: Digest realm="ACSRealm", domain="/acs", nonce="xr9kgAcEiwDHhDbgXC/1A05Af3x2+vVL", algorithm=MD5, qop="auth", stale=false Date: Thu, 01 Jun 2023 06:15:32 GMT Cache-Control: must-revalidate,no-cache,no-store Content-Type: text/html;charset=iso-8859-1 Content-Length: 465 Server: Jetty(9.4.51.v20230217) <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/> <title>Error 401 Unauthorized</title> </head> <body>HTTP ERROR 401 Unauthorized URI: /acs/clarogt/ STATUS: 401 MESSAGE: Unauthorized SERVLET: -
Powered by Jetty:// 9.4.51.v20230217
</body> </html
![](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)