The third session-rational numbers

A rational number is a number that can be expressed as the ratio of two integers. In general, we use approximate decimals. But sometimes, errors are not allowed and two integers must be used to represent a rational number.
At this time, we can create a "rational number class", 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;
		}
	}
	// 加法
	public Rational add(Rational x){
    
    
		return ________________________________________;  //填空位置
	}
	// 乘法
	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;
	}
}

Examples of 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);

Please analyze the code logic, and guess the code at the underline, and submit it through the web page.
Note: Only use the missing code as the answer, and do not fill in the extra code, symbols or explanatory text! !

Pay attention to understanding the meaning of the question, but really look awkward.
What is a rational number? ——Rational numbers are the collective term for integers and fractions. The numbers in the set of rational numbers can be divided into positive rational numbers, negative rational numbers and zero.
Insert picture description here

My rubbish math is really hard to explain in one word.
The idea here is that I divide rational numbers into two parts: numerator ra and denominator rb, and both numerator and denominator are integers. It can be seen from the multiplication operation that (the numerator is multiplied by the numerator, the denominator is multiplied by the denominator), then the addition operation must first be transformed into a number with the same denominator, which requires the division to obtain the smallest common divisor. The numerator of the final result-the numerator of a multiplied by the denominator of b + the denominator of a multiplied by the numerator of b; the denominator-the denominator of a * the denominator of b

答案:new Rational(this.ra * x.rb + this.rb * x.ra, this.rb * x.rb)
end.

Guess you like

Origin blog.csdn.net/weixin_44998686/article/details/109017257