我用这样的构造函数编写了一个自己的分数类:
class Rational {
//A Class representing Rationals
long numerator ;
long denominator;
Rational (long numerator , long denominator) {
this.numerator = numerator ;
this.denominator = denominator;
if (this.denominator < 0) {
this.numerator *= (-1);
this.denominator *= (-1);
}
}
Rational (Rational rational) {
this.numerator = rational.numerator ;
this.denominator = rational.denominator;
if (this.denominator < 0) {
this.numerator *= (-1);
this.denominator *= (-1);
}
}
}
现在我想(例如)将一个分数乘以整数。有没有办法从整数到小数进行隐含的类型转换,以便分子等于给定的整数,分母设置为1.
例如:
Rational rationalOne = new Rational (1L, 2L); //this represents the fraction 1/2
rationalOne.add(2); //add takes a rational as an argument
这个想法是,它从2到2/1被隐式铸造。
感谢您的帮助