相爱不如怀念
2025-06-27 16:08:32
分数类(包含比较方法)
public class Fenshu{
private int fenzi;//分子
private int fenmu; //分母
//构造方法
public Fenshu(int fz,int fm){
this.fenzi=fz;
this.fenmu=fm;
if(fenmu==0) System.out.println("分母不能为0");
}
//属性分子分母的get,set方法
public int getFenzi() {
return fenzi;
}
public int getFenmu() {
return fenmu;
}
public void setFenzi(int fz) {
this.fenzi=fz;
}
public void setFenmu(int fm){
this.fenmu=fm;
}
//get,set方法完毕
public String toString(){//重写toString方法
return this.fenzi+"/"+this.fenmu;
}
//比较大小。用其他分数与当前分数比较
public boolean compare(Fenshu other){
double fs=(double)this.fenzi/(double)this.fenmu;
double fs_other=(double)other.getFenzi()/(double)other.getFenmu();
if(fs-fs_other>0)
{
System.out.println(this+">"+other);
return true;
}
if(fs==fs_other){
System.out.println(this+"="+other);
return true;
}
else {
System.out.println(this+"<"+other);
return false;
}
}
public static void main(String args[]){
Fenshu a=new Fenshu(2,3);
Fenshu b=new Fenshu(1,3);
a.compare(b);
}
}