(1) 复数类Complex 的属性有:
RealPart : int型,代表复数的实数部分
ImaginPart : int型,代表复数的虚数部分
package applet;
import java.applet.*;
import java.awt.*;
public class j_1 extends Applet{
Complex a,b,c,d,e,f;
public void init()
{
a=new Complex(2,2);
b=new Complex(3,4);
c=new Complex();
d=new Complex();
e=new Complex();
f=new Complex();
}
public void paint(Graphics g)
{
c=a.add(b);
d=a.sub(b);
e=a.mul(b);
f=a.div(b);
g.drawString("第一个复数:"+a.ToString(), 10, 50);
g.drawString("第二个复数:"+b.ToString(), 10, 70);
g.drawString("两复数之和:"+c.ToString(), 10, 90);
g.drawString("两复数之差:"+d.ToString(), 10, 110);
g.drawString("两复数相乘:"+e.ToString(), 10, 130);
g.drawString("两复数相除:"+f.ToString(), 10, 150);
}
}
class Complex{
public int realPart;
public int imaginPart;
Complex(int r,int i)
{realPart=r;imaginPart=i;}
Complex(){realPart=0;imaginPart=0;}
Complex add(Complex a)
{
Complex temp=new Complex();
temp.realPart=realPart+a.realPart;
temp.imaginPart=imaginPart+a.imaginPart;
return temp;
}
Complex sub(Complex a)
{
Complex temp=new Complex();
temp.realPart=realPart-a.realPart;
temp.imaginPart=imaginPart-a.imaginPart;
return temp;
}
Complex mul(Complex a)
{
int r,i,ra,ia;
r=this.realPart;
i=this.imaginPart;
ra=a.realPart;
ia=a.imaginPart;
Complex temp=new Complex();
temp.realPart=r*ra-i*ia;
temp.imaginPart=i*ra+r*ia;
return temp;
}
Complex div(Complex a)
{
double r,i,ra,ia;
r=this.realPart;
i=this.imaginPart;
ra=a.realPart;
ia=a.imaginPart;
Complex temp=new Complex();
temp.realPart=(r*ra+i*ia)/(ra*ra+ia*ia);//这个地方应该如何修改,还是说只能改成把类成员变量改成double型数据才可以
temp.imaginPart=(i*ra-r*ia)/(ra*ra+ia*ia);
return temp;
}
public String ToString()
{
if(imaginPart<0)
{
return (realPart+(imaginPart+"i"));
}
else return(realPart+"+"+imaginPart+"i");
}
}
不知道为何要这样做,为什么不用BigDecimal
前面加个类型转换,转成double不就可以了