题目
创建Java程序,进一步学习上述的内容以及关键字this的使用和类抽象的概念。程序要求:
(1)首先创建有理数类Rational,该类包含构造方法和加、减、乘、除方法。
(2)程序主方法中创建两个有理数对象,分别进行加、减、乘、除运算,并输出运算结果。
思路:
(1)按照要求创建一个有理数类Rational,应包含2个私有的长整型数据成员numerator和denominator分别存储一个有理
数的分子和分母;该类应包含不带参数的构造方法,和带参数的构造方法。其中不带参数的构造方法把有理数的分子和分母
初始化为0和1;带参数的构造方法中应对该有理数进行约分,为此需为该类创建一个成员方法private long gcd(long n, l
ong d);该方法返回分子和分母的最大公约数。
(2)为理数类Rational创建四个成员方法分别实现2个有理数的加、减、乘、除运算,四个方法的方法签名如下:
public Rational add(Rational secondRational);
public Rational subtract(Rational secondRational);
public Rational multiply(Rational secondRational);
public Rational divide(Rational secondRational);
(3)为Rational类改写toString()方法,该方法改写后的功能是:以分数的形式输出一个有理数。例如:2/3
(4)创建一个类TestRationalClass,该类中分别创建2个Rational类的对象r1和r2,计算并显示它们的和、
差、积、商。程序运行的结果应如下图所示:
代码
public class TestRational2 {
public static void main(String[] args) {
//创建两个Rational对象
Rational2 r1=new Rational2(3,-1);
Rational2 r2=new Rational2(2,3);
//分别输出加减乘除的结果
System.out.print(r1.toString()+"+ "+r2.toString()+"= ");
System.out.println(r1.add(r2).toString());
System.out.print(r1.toString()+"- "+r2.toString()+"= ");
System.out.println(r1.subtract(r2).toString());
System.out.print(r1.toString()+"* "+r2.toString()+"= ");
System.out.println(r1.multiply(r2).toString());
System.out.print(r1.toString()+"/ "+r2.toString()+"= ");
System.out.println(r1.divide(r2).toString());
}
}
class Rational2{//有理数类
private long numerator; //分子
private long denominator; //分母
public Rational2(long numerator, long denominator) {//约分
long g=gcd(numerator,denominator);
this.numerator = numerator/g;
this.denominator = denominator/g;
}
public Rational2(long numerator) {
this.numerator = numerator;
this.denominator=1;
}
public Rational2() {
this.numerator=0;
this.denominator=1;
}
private long gcd(long n, long d) {//求最小公约数
long temp;
if(n<d) {
temp=n;
n=d;
d=temp;
}
if(n%d==0) {//递归头
return d;
}else {
if(d<0) {
d=-d;
}
return gcd(d,n%d); //递归体
}
}
public Rational2 add(Rational2 secondRational) { //分数加法
long d=this.denominator*secondRational.denominator;
long n=(this.numerator*secondRational.denominator)+(this.denominator*secondRational.numerator);
if(d<0) {
d=-d;
n=-n;
}
return new Rational2(n,d);
}
public Rational2 subtract(Rational2 secondRational) {//分数减法
long d=this.denominator*secondRational.denominator;
long n=this.numerator*secondRational.denominator-this.denominator*secondRational.numerator;
if(d<0) {
d=-d;
n=-n;
}
return new Rational2(n,d);
}
public Rational2 multiply(Rational2 secondRational) {//分数乘法
long d=this.denominator*secondRational.denominator;
long n=this.numerator*secondRational.numerator;
if(d<0) {
d=-d;
n=-n;
}
return new Rational2(n,d);
}
public Rational2 divide(Rational2 secondRational) {//分数除法
long d=this.denominator*secondRational.numerator;
long n=this.numerator*secondRational.denominator;
if(d<0) {
d=-d;
n=-n;
}
return new Rational2(n,d);
}
@Override
public String toString() {
if(denominator==1) {
return numerator+" ";
}else {
return numerator+"/"+denominator+" ";
}
}
}