gpt4 book ai didi

java - 有理数加倍和 GCF

转载 作者:行者123 更新时间:2023-12-01 13:12:02 24 4
gpt4 key购买 nike

这个问题是针对最后一种方法的。每当我在方法“public static Rational Convert(double d)”中返回 d 时,它都会说它无法从 double 转换为 Rational。我该如何做到这一点,以便我能够从方法返回有理数,而无需将“Rational”切换为 double 或参数?这就是我如何实现一个循环来在方法中查找 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;
}

最佳答案

你的 while 循环可能永远不会结束。你永远不会改变分母的值。

现在,对于方法public static Rational Convert(double d)

你返回的是一个 double,Java 如何知道你希望 d 成为一个 Rational?

事实并非如此。

在该方法中,您应该执行更接近的返回:

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

但在此之前,您必须在方法中初始化两者。

你在这里有很多工作要做。

  1. 您将一个double d 传递给该方法,然后不使用该值,只需覆盖它即可。
  2. while(denominator != 0) 中存在无限循环,因为您永远不会更改分母值。
  3. 我假设此方法将被称为 Rational Rational = Rational.convert(someDouble); 因此,您应该考虑在方法内部声明分子和分母,并返回类似 new 的内容有理数(num,dem);

关于java - 有理数加倍和 GCF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22775839/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com