/*创建一个Fractionl类执行分数运算要求: 1.用整形数表示类的private成员变量(f1和f2) 2.提供构造方法,将分子存入f1,分母存入f2 3.提供两个分数相加的运算方法,结果分别存入f1和f2 补充: 4.提供两个分数相减加的运算方法,结果分别存入f1和f2 5.提供两个分数相乘的运算方法,结果分别存入f1和f2 6.提供两个分数相除的运算方法,结果分别存入f1和f2 7.以a/b的形式打印Fraction数 8.以浮点型的形式打印Fraction数 9.编写主控程序运行分数运算*/ public class Fractionl { private int f1; //分子 private int f2; //分母 private Fractionl() {} private Fractionl(int f1,int f2) { this.f1 = f1; this.f2 = f2; } //相加,结果返回一个Fractionl, private Fractionl plug(Fractionl fra) { int fenMu = fra.f2 * f2; int fenZi = fra.f2 * f1 + fra.f1 * f2; int yueshu = oujilide(fenMu, fenZi); int result_fenMu = fenMu / yueshu; int result_fenZi = fenZi / yueshu; Fractionl fractionl = new Fractionl(result_fenZi , result_fenMu); return fractionl; } //相减,结果返回一个Fractionl, private Fractionl subtraction(Fractionl fra) { int fenMu = fra.f2 * f2; int fenZi = fra.f2 * f1 - fra.f1 * f2; int yueshu; if(fenZi < 0) { fenZi = fenZi * -1; yueshu = oujilide(fenMu, fenZi); int result_fenMu = fenMu / yueshu; int result_fenZi = fenZi / yueshu; Fractionl fractionl = new Fractionl(result_fenZi * -1 , result_fenMu); return fractionl; } else { yueshu = oujilide(fenMu, fenZi); int result_fenMu = fenMu / yueshu; int result_fenZi = fenZi / yueshu; Fractionl fractionl = new Fractionl(result_fenZi , result_fenMu); return fractionl; } } //相乘,结果返回一个Fractionl private Fractionl multiplied(Fractionl fra) { int fenMu = fra.f2 * f2; int fenZi = fra.f1 * f1; int yueshu = oujilide(fenMu, fenZi); int result_fenMu = fenMu / yueshu; int result_fenZi = fenZi / yueshu; Fractionl fractionl = new Fractionl(result_fenZi , result_fenMu); return fractionl; } //相除 ,结果返回一个Fractionl private Fractionl divided(Fractionl fra) { int fenMu = fra.f2 * f1; int fenZi = fra.f1 * f2; Fractionl fractionl = new Fractionl(fenZi , fenMu); return fractionl; } //以a/b的形式打印Fraction数 private void printFenshu() { if (f1 == f2) System.out.println("result(分数形式) = 1"); System.out.println("result(分数形式) = "+f1+ "/" + f2); } //8.以浮点型的形式打印Fraction数 private void printXiaoshu() { float result = (float)f1 / (float)f2; System.out.println("result(小数形式) = "+result); } //提取两个数的最大公约数的方法,方法是使用欧几里德算法 private int oujilide(int a,int b) { if(a<b){ int temp; temp=a; a=b; b=temp; } if(0==b) return a; return oujilide(b,a%b); } public static void main(String[] args) { Fractionl fra1 = new Fractionl(3, 5); //表示 3/5 Fractionl fra2 = new Fractionl(5, 6); //表示 5/6 //用于保存结果 Fractionl resultFractionl = new Fractionl(); //相加 resultFractionl = fra1.plug(fra2); resultFractionl.printFenshu(); resultFractionl.printXiaoshu(); // 相减 resultFractionl = fra1.subtraction(fra2); resultFractionl.printFenshu(); resultFractionl.printXiaoshu(); //相乘 resultFractionl = fra1.multiplied(fra2); resultFractionl.printFenshu(); resultFractionl.printXiaoshu(); //相除 resultFractionl = fra1.divided(fra2); resultFractionl.printFenshu(); resultFractionl.printXiaoshu(); } }
作者:c_m_l 发表于2013-5-10 23:19:57 原文链接
阅读:62 评论:0 查看评论