2.定义分数类,包括分子和分母变量、构造方法、 加减乘除方法、化简方法、值计算方法和显示分子和分母的方法。 然后编写一个主类,在其主方法中通过定义两个分数对象来 显示每一个分数的分子值、分母值、化简和值, 显示两个分数加减乘除结果。
package chapter2; public class demo2 { public static void main(String[] args) { Fengshu f1=new Fengshu(12,18); Fengshu f2=new Fengshu(1,6); f1.show(); f1.yuefeng(); f1.show(); Fengshu f3=Fengshu.jia(f1,f2); f3.show(); f3=Fengshu.jian(f1,f2); f3.show(); f3=Fengshu.cheng(f1,f2); f3.show(); f3=Fengshu.chu(f1,f2); f3.show(); } } class Fengshu { int a,b; public Fengshu(int a, int b) { this.a=a; this.b=b; } public void yuefeng() { int a1=this.a; int b1=this.b; while(b1 != 0){ int temp = a1 % b1; a1 = b1; b1 = temp; } this.a=a/a1; this.b=b/a1; } public static Fengshu jia(Fengshu x,Fengshu y) { int ansa,ansb; ansa=x.a*y.b+x.b*y.a; ansb=x.b*y.b; Fengshu ans=new Fengshu(ansa,ansb); return ans; } public static Fengshu jian(Fengshu x,Fengshu y) { int ansa,ansb; ansa=x.a*y.b-x.b*y.a; ansb=x.b*y.b; Fengshu ans=new Fengshu(ansa,ansb); return ans; } public static Fengshu cheng(Fengshu x,Fengshu y) { int ansa,ansb; ansa=x.a*y.a; ansb=x.b*y.b; Fengshu ans=new Fengshu(ansa,ansb); return ans; } public static Fengshu chu(Fengshu x,Fengshu y) { int ansa,ansb; ansa=x.a*y.b; ansb=x.b*y.a; Fengshu ans=new Fengshu(ansa,ansb); return ans; } public void show() { System.out.println(a+"/"+b); } }