面向对象程序设计——Java语言 翁恺 第一周编程作业:设计一个表示分数的类Fraction。这个类用两个int类型的变量分别表示分子和分母。

 

 

//Fraction.java
package Fraction;

class Fraction {
    private int m;
    private int n;
    Fraction(){
        this.m = 1;
        this.n = 1;
    }
    Fraction(int a,int b){
        for( int i=2; i<= a; i++ ){
            if(a%i==0&&b%i==0){
                a/=i;
                b/=i;
            }
        }
        this.m = a;
        this.n = b;
    }

    public int getM() {
        return m;
    }

    public int getN() {
        return n;
    }

    double toDouble(){
        return (double)(this.m/this.n);
    }

    Fraction plus(Fraction r){
        Fraction x = new Fraction();
        if(r.n==this.n){
            x.m=this.m+r.m;
            x.n=this.n;
        }
        else{
            x.n=this.n*r.n;
            x.m=this.m*r.n+r.m*this.n;
        }
//        for( int i=2; i<= x.m; i++ ){
//            if(x.m%i==0&&x.n%i==0){
//                x.n/=i;
//                x.m/=i;
//            }
//        }
        yuefen(x);
        return x;
    }

    Fraction multiply(Fraction r){
        Fraction x = new Fraction();
        x.m = this.m * r.m;
        x.n = this.n * r.n;
//        for( int i=2; i<= x.m; i++ ){
//            if(x.m%i==0&&x.n%i==0){
//                x.n/=i;
//                x.m/=i;
//            }
//        }
        yuefen(x);
        return x;
    }
    void print(){
        if(this.m==this.n) System.out.println(1);
        else System.out.println(this.m+"/"+this.n);
    }
    Fraction yuefen(Fraction x){
        for( int i=2; i<= x.m; i++ ){
            if(x.m%i==0&&x.n%i==0){
                x.n/=i;
                x.m/=i;
            }
        }
        return x;
    }
}
//Main.java
package Fraction;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Fraction a = new Fraction(in.nextInt(), in.nextInt());
        Fraction b = new Fraction(in.nextInt(),in.nextInt());
        a.print();
        b.print();
        a.plus(b).print();
        a.multiply(b).print();
        a.multiply(b).plus(new Fraction(5,6)).print();
        a.print();
        b.print();
        in.close();
    }
}

编写plus函数和multiply函数需创建一个新对象Fraction x以来接收函数中的返回值,plus函数即两个分数相加需注意分母相同(r.n==this.n)的情况,在此情况下,x.n(分母)=this.n=r.n;,x.m在相加即可。但若分母不同,则需通分,我在此并没有把分母通分成最大公倍数,你可以试着通分成最大公倍数,这会减少程序的运行时间。

审题目,会发现在创建分数时就约分了,所以在构造函数中进行约分。并且使用plus函数或者multiply函数也会有约分的需要,但是在这两个函数中进行约分,写两个for循环,那不如再另写一个yuefen函数用来约分。注意约分满足要求是比分子小的整数可以被x.m和x.n整除,必须是x.m%i==0&&x.n%i==0,否则不满足约分。

因为该课程已结课,我无法提交作业,所以不知道是否正确,有错误望指正,感谢!! 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值