集团站切换校区

验证码已发送,请查收短信

复制成功
微信号:togogoi
添加微信好友, 详细了解课程
已复制成功,如果自动跳转微信失败,请前往微信添加好友
打开微信
图标

学习文章

当前位置:首页 > >学习文章 > >

{java培训}复数运算

发布时间: 2017-06-16 10:51:04

要求是实现一个复数类,这个类本身提供四则运算,提示一下,该类结构是:

class Complex {

定义实部、虚部;

构造方法定义;

四则运算方法定义,如加法可定义为:

public Complex add(Complex oper){....}

其它的成员

}

使用该类时,可以

Complex a = new Complex(3.0, 4.), b = new Complex(3.5, 4.5), c;

c = a.add(b);

System.out.println("c="+c);

public class Complex

{

private double realPart;

private double imaginaryPart;

public Complex(double a, double b)

{

this.realPart = a;

this.imaginaryPart = b;

}

public Complex add(Complex a)

{

Complex result = new Complex(this.realPart + a.realPart, this.imaginaryPart + a.imaginaryPart);//(why?)

return result;

}

public Complex decrease(Complex a)

{

Complex result = new Complex(this.realPart - a.realPart, this.imaginaryPart - a.imaginaryPart);//(why?)

return result;

}

public Complex multiply(Complex a)

{

double newReal = this.realPart*a.realPart - this.imaginaryPart * a.imaginaryPart;

double newImaginary = this.realPart*a.imaginaryPart + this.imaginaryPart * a.realPart;

Complex result = new Complex(newReal, newImaginary);

return result;

}

public Complex divide(Complex a)

{

Complex conjugate = new Complex(this.realPart, -this.imaginaryPart);

Complex multiplication = conjugate.multiply(a);

multiplication.realPart /= this.realPart*this.realPart + this.imaginaryPart * this.imaginaryPart;

multiplication.imaginaryPart /= this.realPart*this.realPart + this.imaginaryPart * this.imaginaryPart;

return multiplication;

}

public String toString()

{

String show = this.realPart + " + " + this.imaginaryPart + "i";

return show;

}

public static void main(String [] args)

{

Complex a = new Complex (2, 3);

Complex b = new Complex (1,1);

System.out.println((a.add(b)).toString());

System.out.println((a.decrease(b)).toString());

System.out.println((a.multiply(b)).toString());

System.out.println((a.divide(b)).toString());

 

 

 

 

}

}

上一篇: 以太网交换机的安全问题

下一篇: {java培训}泛型的一个简单例子

十八年老品牌
微信咨询:gz_togogo 咨询电话:18922156670 咨询网站客服:在线客服

相关课程推荐

在线咨询 ×

您好,请问有什么可以帮您?我们将竭诚提供最优质服务!