按照题目要求编写的复数类的Java程序如下
public class Complex{
private float rp;
private float ip;
public Complex(float r ,float i){
rp = r;
ip = i;
}
public Complex() {
rp = 0;
ip = 0;
}
public Complex add(Complex c1 , Complex c2){
rp = c1.rp + c2.rp;
ip = c1.ip + c2.ip;
return this;
}
public Complex subtract( Complex c1,Complex c2){
rp = c1.rp - c2.rp;
ip = c1.ip - c2.ip;
return this;
}
public Complex multiply(Complex c1, Complex c2){
rp = c1.rp*c2.rp - c1.ip*c2.ip;
ip = c1.rp*c2.ip + c1.ip*c2.rp;
return this;
}
public void printComplex(){
System.out.println("("+this.rp+","+this.ip+")");
}
}
package test;
public class Complex {
//浮点型私有变量
private float realPart;
private float imaginaryPart;
//初始化构造方法
public Complex(float a,float b) {
this.setRealPart(a);
this.setImaginaryPart(b);
}
//无参带默认值构造方法
public Complex() {
this.setRealPart(1.0f);
this.setImaginaryPart(1.0f);
}
//加法
public Complex add(Complex c) {
Complex comEntry = new Complex();
comEntry.setRealPart(this.getRealPart()+c.getRealPart());
comEntry.setImaginaryPart(this.getImaginaryPart()+c.getImaginaryPart());
return comEntry;
}
//减法
public Complex sub(Complex c) {
Complex comEntry = new Complex();
comEntry.setRealPart(this.getRealPart()-c.getRealPart());
comEntry.setImaginaryPart(this.getImaginaryPart()-c.getImaginaryPart());
return comEntry;
}
//乘法的公式忘掉了,不好意思
//打印
public void print() {
System.out.println("("+this.getRealPart()+","+this.getImaginaryPart()+"*I)");
}
public float getRealPart() {
return realPart;
}
public void setRealPart(float realPart) {
this.realPart = realPart;
}
public float getImaginaryPart() {
return imaginaryPart;
}
public void setImaginaryPart(float imaginaryPart) {
this.imaginaryPart = imaginaryPart;
}
public static void main(String[] args) {
Complex comEntry1 = new Complex(3.0f,5.0f);
Complex comEntry2 = new Complex(1.0f,2.0f);
comEntry1.print();
comEntry2.print();
comEntry1.add(comEntry2).print();
comEntry1.sub(comEntry2).print();
}
}
看看符不符合你的要求,希望能帮到你。
Vehicle 类有一个doulbe类型的变量speed,用于刻画机动车的速度,一个int型变量power,用于刻画机动车的功率。类中定义了speedUp(int s)方法,体现机动车有加速功能;定义了speedDown()方法,体现机动车有减速的功能;定义了setPower(int p)方法,用于设置机动车的功率;定义了getPower()方法。用于获取机动车的功率。
创建一个复数类
不会再见下一位