Java编写复数类,实现复数的相加和相减

代码如下:

//编写复数类,实现复数相加和相减

public class ComplexNumber {

	private double a;//实部
	private double b;//虚部
	
	public ComplexNumber(double a, double b) {
		
		this.a = a;
		this.b = b;
	}
	
	public ComplexNumber add(ComplexNumber cn) {
		
		this.a += cn.a;
		this.b += cn.b;
		
		return this;//this代表调用该方法的对象
		            //将两个复数相加的结果保存在被加的复数对象中
	}
	
	public ComplexNumber sub(ComplexNumber cn) {
		
		this.a -= cn.a;
		this.b -= cn.b;
		
		return this;
	}
	
	public static void main(String[] args) {
		
		ComplexNumber cn1 = new ComplexNumber(1, 2);
		ComplexNumber cn2 = new ComplexNumber(3, 4);
		
		System.out.println("未进行任何操作时,复数cn1为:" + cn1.a + "+" + cn1.b + "i");
		System.out.println("未进行任何操作时,复数cn2为:" + cn2.a + "+" + cn2.b + "i");
		
		cn1.add(cn2);
		
		System.out.println("执行复数相加操作之后,复数cn1为:" + cn1.a + "+" + cn1.b + "i");
		System.out.println("执行复数相加操作之后,复数cn2为:" + cn2.a + "+" + cn2.b + "i");
		
		cn1.sub(cn2);
		
		System.out.println("执行复数相减操作之后,复数cn1为:" + cn1.a + "+" + cn1.b + "i");
		System.out.println("执行复数相减操作之后,复数cn2为:" + cn2.a + "+" + cn2.b + "i");
	}
}


运行结果:

Java中,我们可以定义一个名为Complex的类来表示复数,并提供加法和减法的操作。下面是一个简单的例子: ```java public class Complex { private double realPart; // 实部 private double imaginaryPart; // 虚部 // 构造函数 public Complex(double real, double imag) { this.realPart = real; this.imaginaryPart = imag; } // 获取实部和虚部的方法 public double getReal() { return realPart; } public double getImaginary() { return imaginaryPart; } // 加法方法 public Complex add(Complex other) { double real = this.realPart + other.realPart; double imag = this.imaginaryPart + other.imaginaryPart; return new Complex(real, imag); } // 减法方法 public Complex subtract(Complex other) { double real = this.realPart - other.realPart; double imag = this.imaginaryPart - other.imaginaryPart; return new Complex(real, imag); } // 打印复数的方法 @Override public String toString() { if (imaginaryPart == 0) { return Double.toString(realPart) + " (实数)"; } else { return Double.toString(realPart) + " + " + imaginaryPart + "i"; } } public static void main(String[] args) { Complex c1 = new Complex(3, 4); Complex c2 = new Complex(1, -2); Complex sum = c1.add(c2); Complex diff = c1.subtract(c2); System.out.println("c1: " + c1); System.out.println("c2: " + c2); System.out.println("c1 + c2: " + sum); System.out.println("c1 - c2: " + diff); } } ``` 在这个例子中,我们定义复数类的属性、构造函数以及基本的算术操作。`add`和`subtract`方法分别计算两个复数的和与差,然后返回新的`Complex`对象。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值