java语言的科学与艺术-Rational(class)
1 /** 2 * The Rational class is used to represent rational numbers, which 3 * are defined to be the quotient of two integer. 4 * @author Administrator 5 * 6 */ 7 public class Rational { 8 /** Creates a new Rational from the integer argument. */ 9 public Rational(){ 10 this(0); 11 } 12 13 /** 14 * Creates a new Rational from the integer argument. 15 * @param n The initial value 16 */ 17 public Rational(int n){ 18 this(n,1); 19 } 20 21 /** 22 * Creates a new Rational with the value x / y. 23 * @param x The numerator of the rational number 24 * @param y The denominator of the rational number 25 */ 26 public Rational(int x, int y) { 27 int g = gcd(Math.abs(x), Math.abs(y)); 28 num = x / g; 29 den = Math.abs(y) / g; 30 if(y < 0) num = -num; 31 } 32 33 /** 34 * Adds the rational number r to this one and returns the sum. 35 * @param r The rational number to be added 36 * @return The sum of the current number and r 37 */ 38 public Rational add(Rational r) { 39 return new Rational(this.num * r.den + r.num * this.den, this.den * r.den); 40 } 41 42 /** 43 * Subtracts the rational number r from this one. 44 * @param r The rational number to be subtracted 45 * @return The result of subtracting r from the current number 46 */ 47 public Rational substract(Rational r) { 48 return new Rational(this.num * r.den - r.num * this.den, this.den * r.den); 49 } 50 51 /** 52 * Multiplies this number by the rational number r. 53 * @param r The rational number used as a multiplier 54 * @return The result of multiplying the current number by r 55 */ 56 public Rational multiply(Rational r) { 57 return new Rational(this.num * r.num, this.den * r.den); 58 } 59 60 /** 61 * Divides this number by the rational number r. 62 * @param r The rational number used as a divisor 63 * @return The result of dividing the current number by r 64 */ 65 66 public Rational divide(Rational r){ 67 return new Rational(this.num * r.den, this.den * r.num); 68 } 69 70 /** 71 * Creates a string representation of this rational number. 72 * @return The string representation of this rational number 73 */ 74 public String toString() { 75 if (den == 1) { 76 return "" + num; 77 } else { 78 return num + "/" + den; 79 } 80 } 81 82 /** 83 * Calculates the greatest common divisor using Euclid's algorithm. 84 * @param x First integer 85 * @param y Second integer 86 * @return The greatest common divisor of x and y 87 */ 88 public int gcd (int x, int y) { 89 int r = x % y; 90 while (r != 0) { 91 x = y; 92 y = r; 93 r = x % y; 94 } 95 return y; 96 } 97 /* Private instance variables */ 98 private int num; /* The numerator of this Rational */ 99 private int den; /* The denominator of this Rational */ 100 }
posted on 2012-12-30 21:46 mybluecode 阅读(546) 评论(0) 编辑 收藏 举报