简体   繁体   English

如何将不适当的分数转换为 Java 中的带分数?

[英]How do I convert an improper fraction to a mixed number in Java?

I'm attempting the ccc j4 or s2 for the 2002 challenge.我正在尝试使用 ccc j4 或 s2 来参加 2002 年的挑战。 I currently have a function to simplify the fraction, but it gives it as a mixed number.我目前有一个简化分数的函数,但它以混合数的形式给出。 The output of that function is a string, and I think I need another function to convert it into a mixed number.该函数的输出是一个字符串,我想我需要另一个函数将其转换为混合数。 Any help would be appreciated.任何帮助,将不胜感激。 Thanks!谢谢!

This is the function I used for converting:这是我用于转换的函数:

public static long gcm(long a, long b) {
  return b == 0 ? a : gcm(b, a % b);
}

public static String asFraction(long a, long b) {
  long gcm = gcm(a, b);
  return (a / gcm) + "/" + (b / gcm);
}

It outputs an improper fraction, but I want a mixed number.它输出一个不正确的分数,但我想要一个带分数。 How can I get this?我怎样才能得到这个? PS English is not my first language. PS 英语不是我的母语。

Since this is part of a challenge, I'll refrain from providing the exact answer, but what I'd focus on is this: A mixed number is an integer followed by a proper fraction.由于这是挑战的一部分,我将避免提供确切的答案,但我要关注的是:带混合数是一个整数,后跟一个适当的分数。 You have an improper fraction.你有一个不正确的分数。 How do you convert improper fractions to mixed numbers?你如何将假分数转换为带分数?

Let's take a simple example, say, 11/4 .让我们举一个简单的例子,比如11/4 How would we write this as a mixed fraction?我们如何将其写为混合分数? We'd write 2 3/4 , because:我们会写2 3/4 ,因为:

  • 2 is the largest integer smaller than 11/4. 2是小于 11/4 的最大整数。
  • 2 is 8/4, leaving 3/4 for the proper fraction. 2是 8/4,留下 3/4 为真分数。
  • Thus the integer part is 2 and the proper fraction is 3/4 , giving us the answer.因此整数部分是2 ,真分数是3/4 ,给了我们答案。

So, given an improper fraction n/d , one way to get a mixed number is to take k = floor[n/d] , and return k + (n - kd)/d .因此,给定一个不正确的分数n/d ,获得混合数的一种方法是取k = floor[n/d] ,并返回k + (n - kd)/d

Hope that helps!希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM