有没有办法知道分数实际上是整数?
Is there way to know that fraction is actually whole number?
我使用 apache 库中的 Fraction
Fraction fraction = Fraction.getFraction(0, 7, 13);
fraction = fraction.multiplyBy(Fraction.getFraction(26));
System.out.print(fraction.getProperWhole());
此代码 returns 14 - 预期结果
Fraction fraction = Fraction.getFraction(0, 7, 13);
fraction = fraction.multiplyBy(Fraction.getFraction(27));
System.out.print(fraction.getProperWhole());
结果也是14,但实际上不是14
有没有办法知道分数实际上是整数
如果您查看 apache 文档,您会看到这个
getProperWhole
public int getProperWhole() Gets the proper whole part of the
fraction.
An improper fraction 7/4 can be resolved into a proper one, 1 3/4.
This method returns the 1 from the proper fraction.
If the fraction is negative such as -7/4, it can be resolved into -1
3/4, so this method returns the positive whole part -1.
Returns: the whole fraction part of a proper fraction, that includes
the sign
所以,你的结果是预期的。
如果你想知道分数是不是整数。
你可以这样做:
f.getNumerator() % f.getDenominator() == 0 ? true : false
因为一个四舍五入的分数作为它的分子是分母的倍数。
作为替代方案,您也可以用 f.reduce()
减少分数,然后检查分母是否等于一。
您似乎在使用 org.apache.commons.lang.math.Fraction
。这有一个 getProperNumerator
方法,当且仅当分数等于整数时 returns 0
。
我使用 apache 库中的 Fraction
Fraction fraction = Fraction.getFraction(0, 7, 13);
fraction = fraction.multiplyBy(Fraction.getFraction(26));
System.out.print(fraction.getProperWhole());
此代码 returns 14 - 预期结果
Fraction fraction = Fraction.getFraction(0, 7, 13);
fraction = fraction.multiplyBy(Fraction.getFraction(27));
System.out.print(fraction.getProperWhole());
结果也是14,但实际上不是14
有没有办法知道分数实际上是整数
如果您查看 apache 文档,您会看到这个
getProperWhole
public int getProperWhole() Gets the proper whole part of the fraction.
An improper fraction 7/4 can be resolved into a proper one, 1 3/4. This method returns the 1 from the proper fraction.
If the fraction is negative such as -7/4, it can be resolved into -1 3/4, so this method returns the positive whole part -1.
Returns: the whole fraction part of a proper fraction, that includes the sign
所以,你的结果是预期的。
如果你想知道分数是不是整数。 你可以这样做:
f.getNumerator() % f.getDenominator() == 0 ? true : false
因为一个四舍五入的分数作为它的分子是分母的倍数。
作为替代方案,您也可以用 f.reduce()
减少分数,然后检查分母是否等于一。
您似乎在使用 org.apache.commons.lang.math.Fraction
。这有一个 getProperNumerator
方法,当且仅当分数等于整数时 returns 0
。