java代码怎么写?

分数类的实现。(比较两个分数大小的程序。)

3个回答

凭凑不齐的情 2025-07-13 14:07:26
public class FenShu{
int fenZi,fenMu;
double value;
FenShu(int fenZi,int fenMu){
this.fenZi=fenZi;
this.fenMu=fenMu;
value=(double)fenZi/fenMu;
}
boolean isGreaterThan(FenShu f){
if(value>f.value){
return true;
}
else{
return false;
}
}
boolean isSmallerThan(FenShu f){
if(value return true;
}
else{
return false;
}
}
boolean isEqualsTo(FenShu f){
if(value==f.value){
return true;
}
else{
return false;
}
}
public static void main(String args[]){
FenShu f1=new FenShu(1,3);
FenShu f2=new FenShu(2,3);
System.out.println(f1.isGreaterThan(f2));
System.out.println(f1.isSmallerThan(f2));
System.out.println(f1.isEqualsTo(f2));
}
}
相爱不如怀念 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);
}
}
唯一的爱情 2025-05-27 18:07:23
class fs
{ int fz;
int fm;
public fs(int z,int m){
fz = z;
fm = m;
}
public bool eq(fs fs1)
{
if(fs1.fz/fs1.fm>this.fz/this.fm)
return true;
else
return false;
}
}