作业:有理数。写好了代码,但不懂得如何约分和正负号的问题。
[code=Java][/code]
package cn.edu.gxu.xingjian.jk10.lishenghua;
import java.util.*;
public class Rational {
private int fenzi;
private int fenmu;
public int getfenzi(){return fenzi;}
public void setfenzi(int fenzi){this.fenzi=fenzi;}
public int getfenmu(){return fenmu;}
public void setY(int fenmu){this.fenmu=fenmu; }
public Rational (int fenzi,int fenmu){
this.fenzi=fenzi;
if(fenmu==0){
System.out.print("fenmu cannot be zero!");
}
this.fenmu=fenmu;
}
public String toString()
{
return ""+fenzi+"/"+fenmu;
}
public Rational add(Rational a){
int finalfenmu=this.fenmu*a.getfenmu();
int finalfenzi=this.fenzi*a.getfenmu()+a.getfenzi()*this.fenmu;
return new Rational(finalfenzi,finalfenmu);
}
public Rational subtract(Rational a){
int finalfenmu=this.fenmu*a.getfenmu();
int finalfenzi=this.fenzi*a.getfenmu()-a.getfenzi()*this.fenmu;
return new Rational(finalfenzi,finalfenmu);
}
public Rational multiply(Rational a){
int finalfenmu=this.fenmu*a.getfenmu();
int finalfenzi=this.fenzi*a.getfenzi();
return new Rational(finalfenzi,finalfenmu);
}
public Rational divide(Rational a){
int finalfenmu=this.fenmu*a.getfenzi();
int fianlfenzi=this.fenzi*a.getfenmu();
return new Rational(fianlfenzi,finalfenmu); }
public int getM(int a,int b){
return fenzi;
}public static void main(String[] args) {
Scanner C=new Scanner(System.in);
System.out.print("Enter the first fenzi=");
int a = C.nextInt();
System.out.print("Enter the first fenmu=");
int b = C.nextInt();
System.out.print("Enter the second fenzi=");
int c = C.nextInt();
System.out.print("Enter the second fenmu=");
int d = C.nextInt();
Rational s=new Rational(a,b);
Rational s1=new Rational(c,d);
Rational s2=s.add(s1);
System.out.println(s+"+"+s1+"="+s2);
Rational s3=s.subtract(s1);
System.out.println(s+"-"+s1+"="+s3);
Rational s4=s.multiply(s1);
System.out.println(s+"*"+s1+"="+s4);
Rational s5=s.divide(s1);
System.out.println(s+"/"+s1+"="+s5);
}
}
------解决方案--------------------
我说一下我的思路。
约分:1.找到分子和分母的最大公约数;
2.分子和分母分别除以它们的最大公约数。
参考代码:
//返回整数a和整数b的最大公约数
public int maxCommonDivisor(int a, int b) {
while(b != 0) {
int k = a % b;
a = b;
b = k;
}
return a;
}
正负号:
{以下执行结果,是你的原始代码的效果。可以看出,负号的显示混乱。}
D:\myjava>java Rational
Enter the first fenzi=1
Enter the first fenmu=2
Enter the second fenzi=-1
Enter the second fenmu=3
1/2+-1/3=1/6
1/2--1/3=5/6
1/2*-1/3=-1/6
1/2/-1/3=3/-2
D:\myjava>java Rational
Enter the first fenzi=1
Enter the first fenmu=-2
Enter the second fenzi=-1
Enter the second fenmu=3
1/-2+-1/3=5/-6
1/-2--1/3=1/-6
1/-2*-1/3=-1/-6
1/-2/-1/3=3/2
{正负号的问题,我也没想出好的解决办法,提供下列方法供参考。}
{这种修改可以实现的效果是,使结果统一为“1/6”或“-1/6”的形式。}
1.添加一个处理正负号问题的方法
public Rational common(int finalfenzi, int finalfenmu) {
Rational rational = new Rational(finalfenzi,finalfenmu);
if(finalfenmu < 0 && finalfenzi > 0 || finalfenmu < 0 && finalfenzi < 0)
rational = new Rational(-finalfenzi,-finalfenmu);
return rational;
}
2.将add、subtract、multiply、divide四个方法的方法体中的代码