这个问题是针对最后一种方法的。每当我在方法“public static Rational convert(double d)”中返回 d 时,它会说它不能从 double 转换为 Rational。我将如何做到这一点,以便我能够从方法中返回一个有理数,而无需将“有理”切换为双精度数或参数?那是我如何实现一个循环来在方法中找到 GCF,而不创建另一个方法吗?
public class Rational
{
// The state of a rational number is just the numerator and denominator.
private static int numerator;
private static int denominator;
// When created, a Rational's numerator and denominator are set.
public Rational( int num, int den )
{
numerator = num;
denominator = den;
}
// Accessor method for the numerator
public int getNumerator( )
{
return numerator;
}
// Accessor method for the denominator
public int getDenominator( )
{
return denominator;
}
// A mutator method which doubles the given rational number by doubling the
// numerator.
public void doubleNumber( )
{
numerator *= 2;
}
// A method which returns the common denominator between the current and
// given rational. Specifically, returns the denominator multiplied by the
// denominator of the given rational number.
public int findCommonDenominator( Rational r )
{
return denominator * r.getDenominator( );
}
//Method returning the decimal value of the fraction.
public static double convert(Rational r)
{
return (double) numerator / (double) denominator;
}
//Method returning the smallest fraction possible from a decimal given.
public static Rational convert(double d)
{
d = (Math.floor(d * 100)/100);
while ( denominator != 0)
{
d = (double) (numerator % denominator);
numerator = denominator;
d = (double) (denominator);
}
return d;
}