Addieren und subtrahieren komplexer zahlen mit OOP-Struktur

Ich habe hier einen code, der gedruckt werden soll aus der Summe und der Differenz zweier komplexer zahlen. Die Anweisungen, die gegeben sind:

stellen Sie die Methoden add, subtract, und print zu void und

testen Sie mit Hilfe des Konstruktors ein Objekt.

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
    }

}

Die erwarteten Antworten sind 12.0 + 13.0 i und -4.0 - 4.0, ich. Bitte helfen Sie mir mit der Methode print. Danke.

  • Was ist das problem? Verwenden System.out.println() eventuell mit String.format()
  • off-topic. warum Sie das hinzufügen von Werten im Konstruktor. warum nicht einfach abtreten?
  • System.aus.println(real + "" + imag +"i");
  • Ich habe versucht, das schon, aber die Ausgabe nur 4.0 + 8.5 ich.
  • Es ist die richtige Ausgabe: c1.add(c2) => 12+13i. dann c1.subtrahieren(c2)=> 12+13i-(8+4.5 i)=4+8.5 i... In der Tat, fügen Sie dann die Subtraktion der gleiche Wert in c1, so dass am Ende c1 ist Links unverändert
  • Ist das problem wirklich mit Ihrer print () - Methode? Wenn Sie immer die falsche Ausgabe, es klingt wie Sie benötigen, um das addieren und subtrahieren und anderen Methoden statt.

Schreibe einen Kommentar