不耻下问:Java语言求分数的化简的代码怎么写
不耻下问:Java语言求分数的化简的代码怎么写
是将2/4化简成1/2这种类型的化简,还是说带有字符的更复杂的化简?
如果是更复杂的化简,那么复杂程度是多少?可否举个例子?
是不是可以把问题转化为:求分子和分母的最大公因数?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Fraction a = new Fraction(in.nextInt(), in.nextInt());
Fraction b = new Fraction(in.nextInt(),in.nextInt());
a.print();
b.print();
a.plus(b).print();
a.multiply(b).plus(new Fraction(5,6)).print();
a.print();
b.print();
in.close();
}
}
class Fraction{
int a,b;
Fraction(int a,int b)
{
this.a = a;
this.b = b;
}
double toDouble()
{
return (double)a/b;
}
Fraction plus(Fraction r)
{
Fraction s = new Fraction(r.a, r.b);
int h = s.b * a;
s.a *= b;
s.b *= b;
s.a += h;
return s;
}
Fraction multiply(Fraction r)
{
r.a *= a;
r.b *= b;
return r;
}
void print()
{
int h;
if(a >= b) h = gcd(a,b);
else h = gcd(b,a);
a /= h;
b /= h;
if(a%b == 0)
System.out.println(a/b);
else
System.out.println(a+"/"+b);
}
int gcd(int m,int n)
{
if(m%n==0) return n;
return gcd(n,m%n);
}
}