对于这个项目,我必须创建一个有理数类,它有两个部分,一个 int 分子和一个 int 分母。我必须添加两个缩略词,其中负分母必须移至分子。我还添加了 getter 和 setter 以及 toString()。数据应打印为分子/分母。我还必须编写用于加法、减法、乘法和除法的成员方法以及否定(?)我不确定最后一部分是什么意思。
我已经完成了课程,但是 Eclipse 在我键入“temp”的部分周围的加法和减法给我一个错误。如果我有任何不正确或遗漏的内容,请告诉我。
public class Rational {
private int numerator;
private int denominator;
public Rational()
{
numerator = 0;
denominator = 1;
}
public Rational(int n, int d, int num, int denom)
{
if (d < 0)
{
num = -n;
denom = d;
}
else if (d == 0)
{
num = n;
denom = 1;
}
else
{
num = n;
denom = 0;
}
}
public int getNumerator()
{
return numerator;
}
public int getDenominator()
{
return denominator;
}
public void setNumerator(int n)
{
numerator = n;
}
public void setDenominator(int n, int d, int num, int denom)
{
denominator = d;
if (d < 0)
{
num = -n;
denom = d;
}
else if (d == 0)
{
num = n;
denom = 1;
}
else
{
num = n;
denom = 0;
}
}
public String toString()
{
return numerator + "/" + denominator;
}
public boolean equals (Rational other)
{
if(numerator * other.denominator == denominator * other.numerator)
return true;
else
return false;
}
public boolean notequals(Rational other)
{
if (numerator * other.denominator != denominator * other.numerator)
return true;
else
return false;
}
//subtract method
public Rational subtract(Rational other)
{
Rational temp;
temp.numerator = numerator * other.denominator - denominator * other.numerator;
temp.denominator = denominator * other.denominator;
return temp;
}
//add method
public Rational add(Rational other)
{
Rational temp;
temp.numerator = numerator * other.denominator + denominator * other.numerator;
temp.denominator = denominator * other.denominator;
return temp;
}
public boolean lessThan(Rational other)
{
return(numerator * other.denominator < denominator * other.numerator);
}
public boolean greterThan(Rational other)
{
return(numerator * other.denominator > denominator * other.numerator);
}
public boolean lessThanEqualTo(Rational other)
{
return(numerator * other.denominator <= denominator * other.numerator);
}
public boolean greaterThanEqual(Rational other)
{
return(numerator * other.denominator >= denominator * other.numerator);
}
}
然而,我正在努力测试每种方法。这是我到目前为止所拥有的:
public class Project4 {
public static void main(String[] args) {
Rational a = new Rational();
Rational b = new Rational();
Rational c;
c = a.add(b);
}
}