public class Main {
public static void main(String[] args) {
Rational a = new Rational(1,3);
Rational b = new Rational(1,6);
Rational c = a.add(b);
// Rational c = a.mul(b);
System.out.println(a + "+" + b + "=" + c);// 1/3+1/6=3/6
}
}
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){
// ra/rb x.rb/x.ra
// 1/3 1/6 6/18 + 3/18 = 9/18 = 1/2
return new Rational(this.ra * x.rb + x.ra * this.rb, this.rb * x.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;
}
}
2013年B省蓝桥第五题JAVA
最新推荐文章于 2024-08-29 18:44:48 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)