1条回答 默认 最新
- yuge_Bwqz 2021-12-04 16:17关注
1.建议楼主直接贴代码,而不是贴图片。
2.。实现一个分数相加功能,给楼主参考,自己做剩余的功能。public class Fraction { //分子 private int numerator; //分母 private int denominator; //符号 private int sign; //取得分子的值 public int getNumerator() { return numerator; } //设置分子的值 public void setNumerator(int numerator) { this.numerator = numerator; } //取得分母的值 public int getDenominator() { return denominator; } //设置分母的值 public void setDenominator(int denominator) { this.denominator = denominator; } //取符号的值 public int getSign() { return sign; } //设置符号的值 public void setSign(int sign) { this.sign = sign; } /** * 不带参数构造函数 * */ public Fraction() { this.sign = 0; this.numerator=0; this.denominator = 1; } /** * 带三个参数的构造函数 * */ public Fraction(int numerator, int denominator, int sign) { this.numerator = numerator; this.denominator = denominator; this.sign = sign; } /** * 将一个分数加在自己之上,并返回自己 * */ public Fraction plus(Fraction f){ //局部变量 int denominator = 0; int numerator = 0; if(this.sign == f.sign){ //相同符号的分数相加,符号无变化 this.sign = f.sign; //分母等于两个数分母相乘 denominator = this.getDenominator() * f.getDenominator(); //分子计算 numerator = this.getNumerator() * f.getDenominator() + f.getNumerator() * this.getDenominator(); }else{ //不同符号的数相加 //分母等于两个数分母相乘 denominator = this.getDenominator() * f.getDenominator(); //比较分子 int numerator0 = this.getNumerator() * f.getDenominator(); int numerator1 = this.getDenominator() * f.getNumerator(); //哪边分子值大,就去那边的符号 if(numerator0 > numerator1){ this.sign = this.sign; //分子计算 numerator = numerator0 - numerator1; }else { this.sign = f.getSign(); //分子计算 numerator = numerator1 - numerator0; } } //赋值 this.setNumerator(numerator); this.setDenominator(denominator); //调用自己的化简函数 来 化简自己 Fraction reduce = this.reduce(this);//每个函数都要调用这个化简函数 //化简之后重新赋值,要么直接返回回 reduce, 但此相加函数要求返回自己,所以要重新赋值。 this.setNumerator(reduce.getNumerator()); this.setDenominator(reduce.getDenominator()); //返回自己 //如不要求返回自己,则可以返回 reduce return this; } //楼主此处提供的函数方法有矛盾; //1.函数如果没有参数,则是处理自己,则返回类型是void,而不是Fraction //此方法应有参数 public Fraction reduce(Fraction f){ //化简过程省略,楼主自己实现 //返回化简之后的分数 return f; } /** * 此方法是Object类的方法,要重写,加上@Override * */ @Override public String toString(){ String result = null; if(this.sign == 0){ result = "0"; }else if(this.sign == 1){ result = this.getNumerator()+"/"+this.getDenominator(); }else { //this.sign == -1 result = "-"+this.getNumerator()+"/"+this.getDenominator(); } return result; } //测试方法 public static void main(String[] args) { // 3/5 Fraction f1 = new Fraction(3,5,1); // 3/8 Fraction f2 = new Fraction(3,8,-1); f1.plus(f2); //此函数会调用 toString()方法 System.out.println(f1); } }
解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥15 MATLAB动图的问题
- ¥15 求差集那个函数有问题,有无佬可以解决
- ¥15 【提问】基于Invest的水源涵养
- ¥20 微信网友居然可以通过vx号找到我绑的手机号
- ¥15 寻一个支付宝扫码远程授权登录的软件助手app
- ¥15 解riccati方程组
- ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
- ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
- ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
- ¥50 树莓派安卓APK系统签名