java计算分类f1_用Java:创建一个Fraction类执行分数运算。要求如下:(1)用整形数表示类的private成员变量:f1和f2.(2)提供构造方法,将分子存入f1和f2,分母存入f2.。...

满意答案

dcebd7a0de6265b6ccae5ead692f1eab.png

yzp0520

2013.04.16

dcebd7a0de6265b6ccae5ead692f1eab.png

采纳率:41%    等级:12

已帮助:5593人

/** 楼主有问题可以继续交流 */

public class Fraction {

public static void main(String[] args) {

//测试代码

Fraction f1 = new Fraction(1, 2);

Fraction f2 = new Fraction(1, 3);

System.out.println("分数f1 ==" + f1);

System.out.println("分数f2 ==" + f2);

System.out.println("分数f1浮点数 ==" + f1.doubleValue());

System.out.println("分数f2浮点数 ==" + f2.doubleValue());

System.out.println("分数f1+f2 ==" + f1.add(f2));

System.out.println("分数f1-f2 ==" + f1.sub(f2));

System.out.println("分数f1*f2 ==" + f1.multiply(f2));

System.out.println("分数f1/f2 ==" + f1.div(f2));

}

private int f1; //分子

private int f2; //分母

public Fraction(int f1, int f2) {

if(f2 == 0){throw new IllegalArgumentException("分母不能为0");}

this.f1 = f1;

this.f2 = f2;

}

/** [+] */

public Fraction add(Fraction other){

int fm = this.f2 * other.f2;

int fz = this.f1 * other.f2 + other.f1 * this.f2;

return new Fraction(fz, fm);

}

/** [-] */

public Fraction sub(Fraction other){

int fm = this.f2 * other.f2;

int fz = this.f1 * other.f2 - other.f1 * this.f2;

return new Fraction(fz, fm);

}

/** [*] */

public Fraction multiply(Fraction other){

int fm = this.f2 * other.f2;

int fz = this.f1 * other.f1;

return new Fraction(fz, fm);

}

/** [/] */

public Fraction div(Fraction other){

if(other.doubleValue() == 0.0 ){

throw new IllegalArgumentException("0不能做为除数");

}

int fm = this.f2 * other.f1;

int fz = this.f1 * other.f2;

return new Fraction(fz, fm);

}

public String toString(){

return f1 + "/" + f2;

}

public double doubleValue(){

return 1.0 * f1 / f2;

}

}

答案补充

//补充 关于约分1

//如果楼主需要约分的话, 把下面3个方法加到类中,下面的测试代码可以放到main方法中测试

/*

Fraction f3 = new Fraction(2,4);

System.out.println("约分前 == " + f3);

f3.predigest();

System.out.println("约分后 == " + f3);

* */

public void predigest(){

Fraction temp = predigest(this);

if(temp == this){

return;

}else{

this.f1 = temp.f1;

this.f2 = temp.f2;

}

}

答案补充

//补充 关于约分2

private static Fraction predigest(Fraction f){

int fz = f.f1;

int fm = f.f2;

if(fz == 0){

return f;

}

int maxDivisor = getMaxDivisor(fz, fm);

fz = (int) (fz / maxDivisor);

fm = (int) (fm / maxDivisor);

return new Fraction(fz, fm);

}

// 求最大公约数

private static int getMaxDivisor(int up, int down){

int min;

int tem = 1;

min = (up < down) ? up : down;

for (int i = 1; i <= min; i++) {

if (up % i == 0 && down % i == 0)

tem = i;

}

return tem;

}

00分享举报

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值