50,144
社区成员




package test.service.user;
public class Fraction {
/** 分子 */
private int molecular;
/** 分母 */
private int denominator;
public Fraction(){};
/**
* 构造方法
* @param molecular 分子
* @param denominator 分母
*/
public Fraction(int molecular,int denominator){
this.molecular = molecular;
this.denominator = denominator;
}
/**
* 加法
* @param 分数a
* @param 分数b
* @return
*/
public static Fraction fractionAdd( Fraction a,Fraction b){
//通分
int denominator_ = a.denominator * b.denominator;
int molecular_ =
a.molecular *(denominator_/a.denominator)
+
b.molecular *(denominator_/b.denominator)
;
int A = molecular_ ;
int B = denominator_;
//求分子分母的最大公因数
while ( A%B != 0 ){
int C = A%B;
A = B;
B = C;
System.out.println(B);
}
//分子和分母都除以最大公因数
return new Fraction(molecular_/B,denominator_/B);
}
public static void main(String[] args) {
Fraction fraction =Fraction.fractionAdd(new Fraction(1,6), new Fraction(2,5));
System.out.println(fraction.molecular +"__"+fraction.denominator);
}
}
public static void main(String[] args) {
System.out.println(new Fraction(1, 3).plus(new Fraction(1, 5)));
}
class Fraction {
int a;
int b;
Fraction(int a, int b) {
this.a = a;
this.b = b;
}
Fraction plus(Fraction another) {
int c = b * another.b / getGCD(b, another.b);
return new Fraction(a * c / b + another.a * c / another.b, c);
}
private static int getGCD(int a, int b) {
int max = Math.max(a, b);
int min = Math.min(a, b);
return min > 0 ? getGCD(min, max % min) : max;
}
@Override
public String toString() {
return a + " " + b;
}
}