Convert this code to c++ code? public class ComplexNumber { private double real; private double imag; //
Question:
Convert this code to c++ code?
public class ComplexNumber { private double real; private double imag; // default constructor public ComplexNumber() { real = imag = 1.0; } // parameterized constructor public ComplexNumber(double r, double i) { real = r; imag = i; } // copy constructor public ComplexNumber(ComplexNumber other){ real = other.real; imag= other.imag; } public double getReal() { return real; } public double getImaginary() { return imag; } // toString method public String toString() { return String.format("%.2f", real)+" + "+String.format("%.2f", imag)+"i"; } // function to add public ComplexNumber add(ComplexNumber other){ ComplexNumber sum = new ComplexNumber(); sum.real = real + other.real; sum.imag = imag + other.imag; return sum; } // function to suntract public ComplexNumber subtract(ComplexNumber other){ ComplexNumber sub = new ComplexNumber(); sub.real = real - other.real; sub.imag = imag - other.imag; return sub; } // function to multiply public ComplexNumber multiplyBy(ComplexNumber other){ ComplexNumber mul = new ComplexNumber(); mul.real = real*other.real + imag*other.imag; mul.imag = imag*other.real + other.imag*real; return mul; } // function to divide public ComplexNumber divideBy(ComplexNumber other){ if(other.real == 0 && other.imag == 0) throw new IllegalArgumentException("Both ral and imaginary part of denominator can not be zero"); ComplexNumber divide = new ComplexNumber(); divide.real=((real*other.real)+(imag*other.imag))/((other.real*other.real)+(other.imag*other.imag)); divide.imag=((imag*other.real)-(real*other.imag))/((other.real*other.real)+(other.imag*other.imag)); return divide; } public boolean isReal(){ return imag ==0; } public boolean isImaginary(){ return real == 0; } } ################## public class ComplexNumberTesting { public static void main(String[] args) { ComplexNumber c1 =new ComplexNumber(2,4); ComplexNumber c2 = new ComplexNumber(4,5); System.out.println("C1: "+c1); System.out.println("C2: "+c2); ComplexNumber sum = c1.add(c2); System.out.println("C1+C2: "+sum); ComplexNumber sub = c1.subtract(c2); System.out.println("C1-C2: "+sub); ComplexNumber mul = c1.multiplyBy(c2); System.out.println("C1*C2: "+mul); ComplexNumber divide = c1.divideBy(c2); System.out.println("C1/C2: "+divide); } }
Java An Introduction To Problem Solving And Programming
ISBN: 9780134462035
8th Edition
Authors: Walter Savitch