# 有理数类的设计

## 有理数类的代码。

package practice;

public class RationalNumber {
private int molecule;   //分子
private int denominator;  //分母

public RationalNumber(int molecule,int denominator){
this.molecule =molecule;
if(denominator==0)          //错误情况输入提示
{
System.out.println("输入错误，分母不能为0");
System.exit(0);
}
else  this.denominator =denominator;
}

public int GetMolecule() {
return this.molecule; //获得分子
}

public int GetDenominator() {
return this.denominator;  //获得分母
}

public void SetMolecule(int molecule) {//设置分子
this.molecule = molecule;
}

public void SetDenominator(int denominator) {//设置分母
this.denominator = denominator;
}

public RationalNumber Reduction() {//约分运算
int m,d;
m=this.molecule;
d=this.denominator;

if(m<d)
{
int temp=m;
m=d;
d=temp;
}

while(d!=0)
{
int temp=m;
m=d;
d=temp%d;
}

this.denominator/=m; //经循环后获得的m为最大公因子
this.molecule/=m;
return this;
}

RationalNumber result=new RationalNumber(0,1);
result.denominator=number2.denominator*this.denominator;
result.molecule=number2.molecule*this.denominator+this.molecule*number2.denominator;
return result.Reduction();             //得到结果后调用约分

}

public RationalNumber Subtraction(RationalNumber number2) {//减法运算
RationalNumber result=new RationalNumber(0,1);
RationalNumber temp=new RationalNumber(0,1);
temp.molecule=-number2.molecule;
temp.denominator=number2.denominator;
return result;
}

public RationalNumber Muiltiply(RationalNumber number2) {//乘法运算
RationalNumber result=new RationalNumber(0,1);
result.molecule=this.molecule*number2.molecule;
result.denominator=this.denominator*number2.denominator;
return result.Reduction();
}

public RationalNumber Division(RationalNumber number2) {//除法运算
RationalNumber temp=new RationalNumber(0,1);
temp.denominator=number2.molecule;
temp.molecule=number2.denominator;
return Muiltiply(temp);   //除以一个数相当于乘上该数的倒数
}

public String toString(){
if(denominator ==1){
return molecule +"";
}else{
return molecule +"/"+ denominator;
} //转化为字符串
}

}


## 测试代码(要在与有理数类不同包的其他类中调用有理数类)

package test;//在不同包中

import practice.RationalNumber;

public class Main {
public static void main(String[] args) {
RationalNumber x = new RationalNumber(4, 9);
RationalNumber y = new RationalNumber(2, 9);

System.out.println("x的分母为："+x.GetDenominator());
System.out.println("x的分子为："+x.GetMolecule());
System.out.println("x = " + x);

System.out.println("y的分母为："+y.GetDenominator());
System.out.println("y的分子为："+y.GetMolecule());
System.out.println("y = " + y);

System.out.println("x + y = " + x.Add(y));
System.out.println("x - y = " + x.Subtraction(y));
System.out.println("x * y = " + x.Muiltiply(y));
System.out.println("x / y = " + x.Division(y));

}
}


• 测试结果

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

C语言的有理数代码中，往往是通过有理数的 数据结构体 + 函数 来实现有理数的相关运算。

### 尝试从代码复用的角度来描述你设计的有理数类。从几个方面讨论：

#### 别人如何复用你的代码?

//不同包中导入有理数类
package test;

import practice.RationalNumber;


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

posted @ 2020-10-04 12:13  郑梦露  阅读(186)  评论(0编辑  收藏  举报