Lab Fraction
package Lab7;public class Fraction
{
private int numerator,denominator;
public Fraction(int newNumerator, int newDenominator )
{
this.numerator=newNumerator;
this.denominator =newDenominator;
}
public Fraction( )
{
this.numerator=0;
this.denominator =1;
}
public static Fraction add(Fraction C1,Fraction C2)
{
Fraction C3 = new Fraction(0,0);
C3.numerator = C1.numerator*C2.denominator + C2.numerator*C1.denominator ;
C3.denominator = C1.denominator*C2.denominator;
int r;
int n=Math.min(C3.numerator,C3.denominator);
int m=Math.max(C3.numerator,C3.denominator);
while(n != 0)
{
r = m % n;
m = n;
n = r;
}
C3.numerator=C3.numerator/m;
C3.denominator=C3.denominator/m;
return C3;
}
public static String toString(Fraction c3)
{
return (Integer.toString(c3.numerator)+"/"+ Integer.toString(c3.denominator));
}
}
----------------------
package Lab7;
public class FractionDemo {
public static void main(String[] args) {
Fraction F1 = new Fraction(9,8);
Fraction F2 = new Fraction(3,8);
Fraction F3 = Fraction.add( F1, F2);
System.out.println(F3.toString(F3));
}
}
0 Comments:
張貼留言
<< Home