The fifth question of Java Blue Bridge Cup 14 years

Java Rational Number Class

A rational number is a number that can be expressed as the ratio of two integers. In general, we use approximate decimal representation. But there are
times when errors are not allowed and two integers must be used to represent a rational number.

At this point, we can establish a "rational number class", and the following code initially achieves this goal. For brevity, it only
provides addition and multiplication operations.

class Rational { private long ra; private long rb;

private long gcd(long a, long b) {
    if (b == 0)
        return a;
    return gcd(b, a % b);
}

public Rational(long a, long b) {
    ra = a;
    rb = b;
    long k = gcd(ra, rb);
    if (k > 1) { // 需要约分
        ra /= k;
        rb /= k;
    }
}

// Addition
public Rational add(Rational x) { return ________________________________________; // fill in the blanks }

// 乘法
public Rational mul(Rational x) { return new Rational(ra * x.ra, rb * x.rb); }

public String toString() {
    if (rb == 1)
        return "" + ra;
    return ra + "/" + rb;
}

}

Example using this class:
Rational a = new Rational(1,3);
Rational b = new Rational(1,6);
Rational c = a.add(b);
System.out.println(a + "+" + b + "=" + c);

public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		Rational a = new Rational(1, 3);
		Rational b = new Rational(1, 6);
		Rational c = a.add(b);
		System.out.println(a + "+" + b + "=" + c);
	}
 
}
 
class Rational {
    
    
	private long ra;
	private long rb;
 
	private long gcd(long a, long b) {
    
    
		if (b == 0)
			return a;
		return gcd(b, a % b);
	}
 
	public Rational(long a, long b) {
    
    
		ra = a;
		rb = b;
		long k = gcd(ra, rb);
		if (k > 1) {
    
     // 需要约分
			ra /= k;
			rb /= k;
		}
	}
 
// 加法
	public Rational add(Rational x) {
    
    
		return new Rational(x.ra * rb + ra * x.rb, x.rb * rb); // 填空位置
	}
 
// 乘法
	public Rational mul(Rational x) {
    
    
		return new Rational(ra * x.ra, rb * x.rb);
	}
 
	public String toString() {
    
    
		if (rb == 1)
			return "" + ra;
		return ra + "/" + rb;
	}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325105433&siteId=291194637
Recommended