满意答案
yzp0520
2013.04.16
采纳率: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分享举报