课外天地 李树青学习天地Java程序语言课件 → 程序代码——支持加减乘除的分数类


  共有17304人关注过本帖树形打印复制链接

主题:程序代码——支持加减乘除的分数类

帅哥哟,离线,有人找我吗?
admin
  1楼 博客 | 信息 | 搜索 | 邮箱 | 主页 | UC


加好友 发短信 管理员
等级:管理员 帖子:1945 积分:26736 威望:0 精华:34 注册:2003/12/30 16:34:32
程序代码——支持加减乘除的分数类  发帖心情 Post By:2009/4/10 9:47:10 [只看该作者]

class Fraction {
        private long numerator;
        private long denominator;

        public Fraction() {
        }

        public Fraction(long n, long d) {
                setFraction(n, d);
        }

        public void setNumerator(long n) {
                numerator = n;
        }

        public long getNumerator() {
                return numerator;
        }

        public void setDenominator(long d) {
                if (d == 0)
                        denominator = 1;
                else
                        denominator = d;
        }

        public long getDenominator() {
                return denominator;
        }

        public void setFraction(long n, long d) {
                setNumerator(n);
                setDenominator(d);
        }

        public String toString() {
                return numerator + "/" + denominator;
        }

        public Fraction plus(Fraction f) {
                Fraction result = new Fraction();
                result.numerator = this.numerator * f.denominator + this.denominator
                                * f.numerator;
                result.denominator = this.denominator * f.denominator;
                return result;
        }

        public Fraction minus(Fraction f) {
                Fraction result = new Fraction();
                result.numerator = this.numerator * f.denominator - this.denominator
                                * f.numerator;
                result.denominator = this.denominator * f.denominator;
                return result;
        }

        public Fraction multiply(Fraction f) {
                Fraction result = new Fraction();
                result.numerator = this.numerator * f.numerator;
                result.denominator = this.denominator * f.denominator;
                return result;
        }

        public Fraction divide(Fraction f) {
                Fraction result = new Fraction();
                result.numerator = this.numerator * f.denominator;
                result.denominator = this.denominator * f.numerator;
                return result;
        }
}

public class Exec {
        public static void main(String[] args) {
                Fraction f1 = new Fraction(2, 3);
                Fraction f2 = new Fraction(1, 5);
                Fraction f3 = f1.plus(f2);
                System.out.println(f3);
                f3=f1.minus(f2);
                System.out.println(f3);
                f3=f1.multiply(f2);
                System.out.println(f3);
                f3=f1.divide(f2);
                System.out.println(f3);
        }
}

[此贴子已经被作者于2010-12-12 08:30:16编辑过]

 回到顶部