编制一个复数类,要求有实部虚部,各种参数构造是,可以求模,可以显示值,定义一个方法将两个复数对象相加,同时编制test类测试程序
class complex
{
public static void main(String[] args) 
{
text first=new text(1,5);
text second=new text(10,-10);
text result1,result2 ;
    result1=first.addComplex;
        System.out.println(result1.moComplex);
        System.out.println(result2.toString);
}}
class text
{private float pReal,pIm;
public text(){
pReal=0;
pIm=0;
}
public text(float real,float im){
pReal=real;
pIm=im;
}
public void addComplex( text a){
    text x=new text();
x.pReal=this.pReal+a.pIm;
x.pIm=this.pIm+a.pIm;
}
public void  moComplex(){
 System.out.println( math.sqrt(pReal*pReal+pIm*pIm));
}
public  void toString(){
if (pIm>0)
{
System.out.println( pReal + "+" + this.pIm + "i"); }
if (pIm==0)
{
System.out.println( pReal);
}
if (pIm<0)
{
        System.out.println( pReal + "-" + pIm + "i");
}
}
};

解决方案 »

  1.   

    稍微改了一下,楼主将就看吧:
    /*
     * Created on 2005-9-25
     *
     * TODO To change the template for this generated file go to
     * Window - Preferences - Java - Code Style - Code Templates
     */
    package io;/**
     * @author slash
     * 
     * TODO To change the template for this generated type comment go to Window -
     * Preferences - Java - Code Style - Code Templates
     */
    class Complex {
        public static void main(String[] args) {
            Text first = new Text(1, 5);
            Text second = new Text(10, -10);
            Text result1 = first.add(second);
            System.out.println(result1);
            System.out.println(result1.moComplex());
        }}class Text {    private float pReal, pIm;    public Text() {
            pReal = 0;
            pIm = 0;
        }    public Text(float real, float im) {
            pReal = real;
            pIm = im;
        }    public Text add(Text a) {        pReal += a.pReal;
            pIm += a.pIm;
            return this;
        }    public float moComplex() {        return (float) Math.sqrt(pReal * pReal + pIm * pIm);    }    public String toString() {
            if (pIm != 0)
                return pReal + "" + pIm + "i";
            else
                return "" + pIm;    }
    }
      

  2.   

    建议楼主尽量少用float,这个不精确