Adding and subtract complex numbers using OOP structure

为君一笑 提交于 2019-12-02 09:05:47

Perhaps this is not what you're looking for, but to make the number be printed isn't enough to make something like this in your print method?

System.out.print("The number is: " +real +"+i" +imag);

   public void print(){
     if(this.imag <0){
      System.out.println(this.real+" "+this.imag+"i");
     }
     if(this.imag >0){
      System.out.println(this.real+"+"+this.imag+"i");
     }
    }

You incorrectly use print merhod. if you want to see correct result you need to rewrite add method like this:

public void add(Complex num, Complex num2){
    this.real = num.real + num2.real;
    this.imag = num.imag + num2.imag;
}

rewrite subtract method also.

public void subtract(Complex num){
    this.real = real - num.real;
    this.imag = imag - num.imag;
}

Now main method look like this:

public static void main(String[] args) {
        Complex c1 = new Complex(4.0, 8.5);
        Complex c2 = new Complex(8.0, 4.5);
        Complex result = new Complex(8.0, 4.5);
        result.add(c1,c2);

        result.print();

        result.subtract(c1,c2);
        result.print();

print method as I told previously look like:

public void print(){
    System.out.println(real + " " + imag +"i");
}

Explanation:

In your code you have error. You add c2 to c1 and then subtract c2 frim c1 and then print result. Mathematically this looks like : c1= c1+c2-c2;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!