虚数类

虚数类

(Complex Numbers) Create a class called Complex for performing arithmetic with complex numbers. Complex numbers have the form

realPart + imaginaryPart * i

where i is
√–1

Write a program to test your class. Use floating-point variables to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it’s declared. Provide a no-argument constructor with default values in case no initializers are provided. Providepublic methods that perform the following operations:

a) Add two Complex numbers: The real parts are added together and the imaginary parts are added together.

b) Subtract two Complex numbers: The real part of the right operand is subtracted from the real part of the left operand, and the imaginary part of the right operand is sub- tracted from the imaginary part of the left operand.

c) Print Complex numbers in the form (realPart, imaginaryPart).

`public class Complex {
	private double realPart;
	private double imaginaryPart;
	public Complex(double realPart,double imaginaryPart ){
		this.realPart = realPart;
		this.imaginaryPart = imaginaryPart;
	}
	public Complex(){
		this.realPart = 1.0;
		this.imaginaryPart = 1.0;
	}
	public static Complex add(Complex cn1,Complex cn2) {
		double sumOfRealPart = cn1.realPart+cn2.realPart;
		double sumOfImaginry = cn1.imaginaryPart+cn2.imaginaryPart;
		return new Complex(sumOfRealPart,sumOfImaginry);
	}
	public static Complex subtract(Complex cn1,Complex cn2) {
		double sumOfRealPart = cn1.realPart-cn2.realPart;
		double sumOfImaginary = cn1.imaginaryPart-cn2.imaginaryPart;
		return new Complex(sumOfRealPart,sumOfImaginary);
	}
	public void ac() {
		System.out.println("("+this.realPart+","+this.imaginaryPart+")");
	}
}


import homework.Complex;
public class ComplexTest {
	public static void main(String[] args) {
		Complex cn1 = new Complex(10.50,50.107);
		Complex cn2 = new Complex(1.0923,-3.0);

		System.out.print("Complex1 = ");
		cn1.ac();
		System.out.print("Complex2 = ");
		cn2.ac();

		System.out.print("Complex1+Complex2 = ");
		Complex.add(cn1, cn2).ac();
		System.out.print("Complex1-Complex2 = ");
		Complex.subtract(cn1, cn2).ac();
	}
}
发布了4 篇原创文章 · 获赞 1 · 访问量 21

猜你喜欢

转载自blog.csdn.net/lalalaAuraro/article/details/105220686