-1

我这里有一个代码,应该打印两个复数的和和差。给出的说明是: 使用构造函数的对象
使方法add、、subtractprint成为void和测试。


public class Complex {

    /**
     * @param args
     */
    public double real;
    public double imag;
    public String output = "";

    public Complex(double real, double imag){
        this.real += real;
        this.imag += imag;
    }

    public Complex(){
        real = 0;
        imag = 0;
    }

    public double getReal(){
        return real;
    }

    public void setReal(double real){
        this.real = real;
    }

    public double getImag(){
        return imag;
    }

    public void setImag(double imag){
        this.imag = imag;
    }

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

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

    public void print(){
        //
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Complex c1 = new Complex(4.0, 8.5);
        Complex c2 = new Complex(8.0, 4.5);

        c1.add(c2);
        c1.subtract(c2);
        c1.print(); //expected answer 12.0 + 13.0i
                                    //-4.0 - 4.0i
    }

}



预期的答案是 12.0 + 13.0i 和 -4.0 - 4.0i。请帮助我的方法print。谢谢你。

4

3 回答 3

0

也许这不是您要寻找的,但是要打印数字还不足以在您的打印方法中进行类似的操作?

System.out.print("编号为:" +real +"+i" +imag);

于 2013-08-31T17:28:55.510 回答
0
   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");
     }
    }
于 2013-08-31T17:31:36.583 回答
0

您错误地使用了 print merhod。如果你想看到正确的结果,你需要重写 add 方法,如下所示:

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

也重写减法。

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

现在主要方法如下所示:

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

我之前告诉过的打印方法如下所示:

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

解释:

在您的代码中,您有错误。您将 c2 添加到 c1,然后减去 c2 frim c1,然后打印结果。数学上看起来像:c1= c1+c2-c2;

于 2013-08-31T17:35:34.727 回答