java 抽象一个复数类

抽象一个复数类

– 成员变量:实部real、虚部image;

– 构造方法:赋初值;

– 成员方法:加法运算

​ FuShu add(FuShu s1);

–成员方法:打印输出复数

• Test类

–主方法main:两个复数相加,输出结果。

题解

class FuShu{
    int real; //实部real、虚部image;
    int image;
    FuShu(int real, int image) { //构造方法:赋初值;
        this.real = real;
        this.image = image;
    }

    FuShu add(FuShu s1) { // 加法运算 FuShu add(FuShu s1);
        FuShu tmp = new FuShu(real + s1.real, image + s1.image);
        return tmp;
    }
}

public class FuNumber01 { 
    public static void main(String[] args) { //两个复数相加,输出结果
        FuShu s1 = new FuShu(1, 2);
        FuShu s2 = new FuShu(2, 3);
        FuShu s3 = s2.add(s1);
        System.out.println(s3.real + " + " + s3.image + "i");
    }

}

运行结果

3 + 5i
posted @ 2021-07-11 00:18  SKPrimin  阅读(43)  评论(0编辑  收藏  举报