Java中一个分数类的简单设计 - 编程入门网
作者 佚名技术
来源 NET编程
浏览
发布时间 2012-06-18
inator == 1) {
System.out.println(f.numerator);
return;
}
StringBuilder sb = new StringBuilder();
sb.append(f.numerator);
sb.append(''/'');
sb.append(f.denominator);
System.out.println(sb.toString());
}
public static void output(String s) {
System.out.println(s);
}
private static Fraction StringToFraction(String s) {
String[] ss = s.split("/");
try {
if (ss.length == 2)
return simpler(new Fraction(Integer.valueOf(ss[0]), Integer
.valueOf(ss[1])));
else if (ss.length == 1)
return new Fraction(Integer.valueOf(ss[0]));
else
return null;
} catch (NumberFormatException e) {
output("Usage: Should input one fraction or two fractions and a operator with the style ''f1 + f2''");
}
return null;
}
/**
* both the numerator and denominator are divided by GCD
*/
private static Fraction simpler(Fraction f) {
int gcd = GCD(f.numerator, f.denominator);
if (gcd > 1)
return new Fraction(f.numerator / gcd, f.denominator / gcd);
else
return f;
}
/**
* reduction to common denominator
*/
private static Fraction[] RCD(Fraction f1, Fraction f2) {
int lcm = LCM(f1.denominator, f2.denominator);
int m = lcm / f1.denominator;
if (m > 1)
f1 = new Fraction(f1.numerator * m, f1.denominator * m);
m = lcm / f2.denominator;
if (m > 1)
f2 = new Fraction(f2.numerator * m, f2.denominator * m);
return new Fraction[] { f1, f2 };
}
/**
* greatest common divisor
*/
private static int GCD(int s, int b) {
// s-small,b-big
if (s > b) {
int temp = s;
s = b;
b = temp;
}
while (b != 0) {
int temp = s % b;
s = b;
b = temp;
}
return s;
}
/**
* a lowest common multiple
*/
private static int LCM(int a, int b) {
return a * b / GCD(a, b);
}
public static void main(String[] args) throws IOException {
int c;
StringBuilder sb = new StringBuilder();
while ((c = System.in.read()) != ''\n'')
sb.append((char) c);
input(sb.toString());
}
}
本文出自 “子 孑” 博客,请务必保留此出处http://zhangjunhd.blog.51cto.com/113473/77859 |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |
你可能对下面的文章感兴趣
关于Java中一个分数类的简单设计 - 编程入门网的所有评论