?? complex.java
字號:
//【習3.4】 復數類。
public class Complex
{
private double real,im; //實部,虛部
public Complex(double real, double im) //構造方法
{
this.real = real;
this.im = im;
}
public Complex(double real) //構造方法重載
{
this(real,0);
}
public Complex()
{
this(0,0);
}
public Complex(Complex c) //拷貝構造方法
{
this(c.real,c.im);
}
public boolean equals(Complex c) //比較兩個對象是否相等
{
return this.real==c.real && this.im==c.im;
}
public String toString()
{
return "("+this.real+"+"+this.im+"i)";
}
public void add(Complex c) //兩個對象相加
{ //改變當前對象,沒有返回新對象
this.real += c.real;
this.im += c.im;
}
public Complex plus(Complex c) //兩個對象相加,與add()方法參數一樣不能重載
{ //返回新創建對象,沒有改變當前對象
return new Complex(this.real+c.real, this.im+c.im);
}
public void subtract(Complex c) //兩個對象相減
{ //改變當前對象,沒有返回新對象
this.real -= c.real;
this.im -= c.im;
}
public Complex minus(Complex c) //兩個對象相減,與subtract()方法參數一樣不能重載
{ //返回新創建的對象,沒有改變當前對象
return new Complex(this.real-c.real, this.im-c.im);
}
}
class Complex__ex
{
public static void main(String args[])
{
Complex a = new Complex(1,2);
Complex b = new Complex(3,5);
Complex c = a.plus(b); //返回新創建對象
System.out.println(a+" + "+b+" = "+c);
}
}
/*
程序運行結果如下:
(1.0+2.0i) + (3.0+5.0i) = (40.0+7.0i)
*/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -