1

这个问题是针对最后一种方法的。每当我在方法“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;  
}
4

1 回答 1

1

Your while loop will probably never end. You never change the value of denominator.

Now, for the method public static Rational convert(double d)

You're returning a double, how does Java know that you want d to be a Rational?

It doesn't.

In that method you should be doing a return closer to:

Rational converted = new Rational(numerator, denominator);
return converted;

But before you do that you have to initialize both in the method.

You have a lot of work to do here.

  1. You pass a double d to the method, then don't use the value, just overwrite it.
  2. You have an endless loop in while(denominator != 0) because you never change denominators value.
  3. I assume this method would be called as Rational rational = Rational.convert(someDouble); So you should consider declaring a numerator and denominator inside of the method, and returning something like new Rational(num,dem);
于 2014-04-01T03:30:17.877 回答