Adding and subtract complex numbers using OOP structure

前端 未结 3 1786
醉酒成梦
醉酒成梦 2021-01-29 10:07

I have here a code that should print the sum and difference of two complex numbers. The instructions given are:
make the methods add, subtract, and

相关标签:
3条回答
  • 2021-01-29 10:26
       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");
         }
        }
    
    0 讨论(0)
  • 2021-01-29 10:29

    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);

    0 讨论(0)
  • 2021-01-29 10:44

    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;

    0 讨论(0)
提交回复
热议问题