วันจันทร์ที่ 27 ตุลาคม พ.ศ. 2557

Lab 5 - class Complex Number



void setup(){
  Complex a = new Complex(5,7);
  Complex b = new Complex(2,4);
  Complex z,y;
  println(a.toString());
  z = a.addComplex(b);
  println(z.toString());
  y = b.subtractComplex(a);
  println(y.toString());
}
class Complex{
  int real;
  int imagine;
  Complex(int real,int imagine){
    this.real = real;
    this.imagine = imagine;
  }
  Complex addComplex(Complex x){
    int r,i;
    r = this.real + x.real;
    i = this.imagine + x.imagine;
    Complex c = new Complex(r,i);
    return c;
  }
  Complex subtractComplex(Complex x){
    int r,i;
    r = this.real - x.real;
    i = this.imagine - x.imagine;
    Complex c = new Complex(r,i);
    return c;
  }
  String toString(){
    String s="";
    if(this.real!=0){
      s = s+this.real;
    }
    if(this.imagine!=0){
      if(this.imagine>0){
        s = s+"+";
      }
      s = s+this.imagine+"i";
    }
    return s;
  }
}