. 创建一个复数类Complex,对复数进行数学运算

该博客介绍了一个Java实现的复数类Complex,包括带参数和默认值的构造方法,以及复数的加、减、乘运算。通过示例展示了如何创建复数对象并进行数学运算,最后将结果按照特定格式输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【问题描述】
创建一个复数类Complex,对复数进行数学运算,复数具有如下格式:realPart+imaginaryPart*i,其中,i为-1的平方根,具体要求如下:
(1)利用浮点变量表示此类的私有数据。提供两个构造方法,一个用于此类声明时对象的初始化;一个为带默认值得无参构造方法。
(2)提供两复数加、减、乘的运算方法。
(3)按格式(a,b)打印复数,其中a为实部,b为虚部。


import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.println("input c1:");
		double r1 = in.nextDouble();
		double ima1 = in.nextDouble();
		System.out.println("input c2:");
		double r2 = in.nextDouble();
		double ima2 = in.nextDouble();
		Complex c1 = new Complex(r1, ima1);
		Complex c2 = new Complex(r2, ima2);
		System.out.println("ComplexNumber a: "+c1);
		System.out.println("ComplexNumber b: "+c2);
		System.out.println("(a + b) = " + c1.add(c2));
		System.out.println("(a - b) = " + c1.sub(c2));
		System.out.println("(a * b) = " + c1.mul(c2));

	}
}

class Complex {
	private double real, imaginary;

	Complex(double r, double i) {
		this.imaginary = i;
		this.real = r;
	}

	Complex() {

	}

	public Complex add(Complex other) {
		Complex t = new Complex(0, 0);
		t.real = this.real + other.real;
		t.imaginary = this.imaginary + other.imaginary;
		return t;
	}

	public Complex sub(Complex other) {
		Complex t = new Complex(0, 0);
		t.real = this.real - other.real;
		t.imaginary = this.imaginary - other.imaginary;
		return t;
	}

	public Complex mul(Complex other) {
		Complex t = new Complex(0, 0);
		t.real = this.real * other.real - this.imaginary * other.imaginary;
		t.imaginary = this.real * other.imaginary + this.imaginary * other.real;
		return t;
	}

	public String toString() {
		return real + " + " + imaginary + "i";
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值