|
|
发表于 2023-10-27 19:13:35
|
显示全部楼层
函数接口定义:
[/code]java
class TDVector {
private double x;
private double y;
// 无参构造方法
public TDVector() {
this.x = 0;
this.y = 0;
}
// 带参构造方法
public TDVector(double x, double y) {
this.x = x;
this.y = y;
}
// 拷贝构造方法
public TDVector(TDVector vector) {
this.x = vector.x;
this.y = vector.y;
}
// 获取x的值
public double getX() {
return this.x;
}
// 获取y的值
public double getY() {
return this.y;
}
// 设置x的值
public void setX(double x) {
this.x = x;
}
// 设置y的值
public void setY(double y) {
this.y = y;
}
// 向量相加
public TDVector add(TDVector other) {
double sumX = this.x + other.x;
double sumY = this.y + other.y;
return new TDVector(sumX, sumY);
}
// 字符串表示形式
public String toString() {
return "(" + this.x + "," + this.y + ")";
}
}
[/code]
主程序部分:
[/code]java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
TDVector a = new TDVector(); // 无参构造,向量的x和y默认为0
Scanner sc = new Scanner(System.in);
double x, y, z;
x = sc.nextDouble();
y = sc.nextDouble();
z = sc.nextDouble();
TDVector b = new TDVector(x, y); // 按照参数构造向量的x和y
TDVector c = new TDVector(b); // 按照向量b构造向量
a.setY(z);
System.out.println(a);
System.out.println(b);
System.out.println(c);
c.setX(z);
a = b.add(c);
System.out.println(a);
System.out.println("b.x=" + b.getX() + " b.y=" + b.getY());
sc.close();
}
}
[/code]
输入样例:
[/code]
3.14 1.9 2.72
[/code]
输出样例:
[/code]
(0.0,2.72)
(3.14,1.9)
(3.14,1.9)
(5.86,3.8)
b.x=3.14 b.y=1.9
[/code]
这个题目是关于二维向量类的定义和使用。在代码中,TDVector是一个包含x和y坐标的二维向量类。你需要完成该类的构造方法、获取和设置坐标的方法,以及向量相加的方法。然后在Main类中实例化对象并进行操作,最后输出结果。
球一个最佳答案谢谢啦!这对我非常重要!   |
|