首页 > 代码库 > 有理数类

有理数类

 1 public class Rational {
 2 
 3     private int numerator;
 4     private int denominator;
 5 
 6     public Rational(int aNumerator, int aDenominator){
 7         int r = gcd(aDenominator, aNumerator);
 8         numerator = aNumerator / r;
 9         denominator = aDenominator / r;
10         sign();
11     }
12 
13     private static int gcd(int a, int b){
14         if(b == 0){
15             return a;
16         }
17         else{
18             return gcd(b, a % b);
19         }
20     }
21 
22     private void sign(){
23         if(denominator < 0){
24             numerator = -numerator;
25             denominator = -denominator;
26         }
27     }
28 
29     public Rational plus(Rational b){
30         int d = this.denominator * b.denominator;
31         int n = this.numerator * b.denominator + b.numerator * this.denominator;
32         return new Rational(n, d);
33     }
34 
35     public Rational minus(Rational b){
36         int d = this.denominator * b.denominator;
37         int n = this.numerator * b.denominator - b.numerator * this.denominator;
38         return new Rational(n, d);
39     }
40 
41     public Rational times(Rational b){
42         int d = this.denominator * b.denominator;
43         int n = this.numerator * b.numerator;
44         return new Rational(n, d);
45     }
46 
47     public Rational divides(Rational b){
48         return times(new Rational(b.denominator, b.numerator));
49     }
50 
51     public boolean equals(Object b){
52         if(this == b)return true;
53         if(b == null)return false;
54         if(this.getClass() != b.getClass())return false;
55 
56         Rational that = (Rational)b;
57         if(this.numerator == that.numerator && this.denominator == that.denominator)return true;
58         return false;
59     }
60 
61     public String toString(){
62         return this.numerator + "/" + this.denominator;
63     }
64 
65     public static void main(String[] args) {
66         Rational a = new Rational(8, 30);
67         Rational b = new Rational(32, 40);
68         System.out.println("a = " + a);
69         System.out.println("b = " + b);
70         System.out.println("a + b = " + a.plus(b));
71         System.out.println("a - b = " + a.minus(b));
72         System.out.println("b - a = " + b.minus(a));
73         System.out.println("a * b = " + a.times(b));
74         System.out.println("a / b = " + a.divides(b));
75         System.out.println("b / a = " + b.divides(a));
76         System.out.println("a == b? " + (a.equals(b) == true? "true":"false"));
77     }
78     
79 }