有理数类的设计

一、有理数类代码

package code;

public class RationalNum {

private int Numerator;//分子
private int Denominator;//分母

public RationalNum(int Numerator, int Denominator) {	//构造函数
this.Numerator=Numerator;
this.Denominator=Denominator;
}

public int getNumerator() {	//获取分子
return Numerator;
}

public void setNumerator(int numerator) {
Numerator = numerator;
}

public int getDenominator() {	//获取分母
return Denominator;
}

public void setDenominator(int denominator) {
Denominator = denominator;
}

public	RationalNum addition(RationalNum R2) {	//加法
int n=this.Numerator*R2.Denominator+R2.Numerator*this.Denominator;
int d=this.Denominator*R2.Denominator;
return new RationalNum(n,d);
}

public	RationalNum subtraction(RationalNum R2) {	//减法
int n=this.Numerator*R2.Denominator-R2.Numerator*this.Denominator;
int d=this.Denominator*R2.Denominator;
return new RationalNum(n,d);
}

public	RationalNum multiplication(RationalNum R2) {	//乘法
int n=this.Numerator*R2.Numerator;
int d=this.Denominator*R2.Denominator;
return new RationalNum(n,d);
}

public	RationalNum division(RationalNum R2) {	//除法
int n=this.Numerator*R2.Denominator;
int d=this.Denominator*R2.Numerator;
return new RationalNum(n,d);
}

public boolean equals(RationalNum R2) {	//判断是否相等
if(this.subtraction(R2).getNumerator()==0)
return true;
else
return false;
}
public int compareTo(RationalNum R2) {	//比较大小
if(this.subtraction(R2).getNumerator()>0)
return 1;
else if(this.subtraction( R2).getNumerator()==0)
return 0;
else
return -1;
}

public String toString() {	//转换成String型
if(this.Denominator==1)
return this.Numerator+" ";
else
return this.Numerator+"/"+this.Denominator;
}

public double doubleValue() {	//转换成double型
return this.Numerator*1.0/this.Denominator;
}

public int intValue() {	//转换成int型
return (int)doubleValue();
}

public long longValue() {	//转换成long型
return (long)doubleValue();
}

public float floatValue() {	//转换成float型
return (float)doubleValue();
}
}


二、测试代码

package test;

import code.RationalNum;

public class Test {

public static void main(String[] arr) {
RationalNum R1=new RationalNum(1,2);
RationalNum R2=new RationalNum(3,4);
System.out.println(R1.subtraction(R2));
System.out.println(R1.multiplication(R2));
System.out.println(R1.division(R2));
System.out.println(R1.equals(R2));
System.out.println(R1.compareTo(R2));
System.out.println(R1.toString());
System.out.println(R1.doubleValue());
System.out.println(R1.intValue());
System.out.println(R1.longValue());
System.out.println(R1.floatValue());
}
}


三、尝试描述怎么与c语言的有理数代码相比较,为什么你设计的类更加面向对象?

C语言是面向过程的，用来编写要干什么的，而Java是面向对象的，可以调用多个方法，用来编这个对象能干什么的。所以Java比起C语言更面向对象。

四、讨论

c.有理数类的public方法是否设置合适?为什么有的方法设置为private?

posted @ 2020-10-04 02:59  awwman  阅读(95)  评论(0编辑  收藏  举报