编写一个Java应用程序,实现两个有理数的四则运算,要求有理数用分子和分母的形式表示。结果要求用“分子/分母”的形式表示。
求源代码
1 回答
已采纳
winner4265975
TA贡献19条经验 获得超17个赞
public class Arithmetic { private int a; private int b; private int c; private int d; //两个有理数分别是a/b和c/d; public Arithmetic(int a,int b,int c,int d){ super(); if(b==0||d==0) throw new RuntimeException("分母不能为零"); this.a=a; this.b=b; this.c=c; this.d=d; } public String add(){ int remainder=greatestCommonDivisor(Math.abs(a*d+c*b),Math.abs(b*d)); return showAsFraction((a*d+c*b)/remainder,b*d/remainder); } public String sub(){ int remainder=greatestCommonDivisor(Math.abs(a*d-c*b),Math.abs(b*d)); return showAsFraction((a*d-c*b)/remainder,b*d/remainder); } public String multiply(){ int remainder=greatestCommonDivisor(Math.abs(a*c),Math.abs(b*d)); return showAsFraction(a*c/remainder,b*d/remainder); } public String divide(){ int remainder=greatestCommonDivisor(Math.abs(a*d),Math.abs(b*c)); return showAsFraction(a*d/remainder,b*c/remainder); } //求最大公约数 public int greatestCommonDivisor(int numerator ,int denominator){ int bigger; int smaller; if(numerator>denominator){ bigger=numerator; smaller=denominator; }else{ bigger=denominator; smaller=numerator; } int remainder=bigger%smaller; while(remainder!=0){ bigger=smaller; smaller=remainder; remainder=bigger%smaller; } return smaller; } public String showAsFraction(int numerator ,int denominator){ if((numerator>0&&denominator>0)||(numerator<0&&denominator<0)) return Math.abs(numerator)+"/"+Math.abs(denominator); else return "-"+Math.abs(numerator)+"/"+Math.abs(denominator); } }
纯手打望采纳!
添加回答
举报
0/150
提交
取消