简体   繁体   English

Java中的分数

[英]Fraction in Java

I don't know how to represent fractions.我不知道如何表示分数。 I'm supposed to add two fractions together based off of the numerators and denominators that the user inputs for both fractions.我应该根据用户为两个分数输入的分子和分母将两个分数相加。 What the activity is asking me to do is have this as the printed outcome.活动要求我做的是将此作为打印结果。

What is the numerator of the first fraction?第一个分数的分子是什么? 1 1

What is the denominator of the first fraction?第一个分数的分母是什么? 2 2

What is the numerator of the second fraction?第二个分数的分子是什么? 2 2

What is the denominator of the second fraction?第二个分数的分母是什么? 5 5

The sum of 1/2 + 2/5 = 9/10 1/2 + 2/5 = 9/10 之和

The numbers after the questions can be changed based on user input.问题后面的数字可以根据用户输入进行更改。

Below you can see what I have written.你可以在下面看到我写的内容。

public class AddFractions extends ConsoleProgram
{
     public void run()
     {
         int numeratorFirst = readInt("What is the numerator of the first fraction?");
         int denominatorFirst = readInt("What is the denominator of the first fraction?");
         int numeratorSecond = readInt("What is the numerator of the second fraction?");
         int denominatorSecond = readInt("What is the denominator of the second fraction?");       
     }
}

You can add two fractions after you convert them to a common denominator.将两个分数转换为公分母后,您可以将它们相加。 The easiest way to do this is:最简单的方法是:

  1. Multiply the first numerator by the second denominator.将第一个分子乘以第二个分母。
  2. Multiply the second numerator by the first denominator.将第二个分子乘以第一个分母。
  3. Multiply the denominators together to get the common denominator.将分母相乘得到公分母。
  4. Add the numerators.添加分子。
  5. Reduce the resulting fraction if necessary.如有必要,减少所得分数。 (Check to see if the denominator is evenly divisible by the numerator, or vice-versa if the numerator is bigger.) (检查分母是否可以被分子整除,如果分子较大,则反之亦然。)

When adding fractions, you have to make sure they share a common denominator, then add the numerators.添加分数时,您必须确保它们共享一个公分母,然后添加分子。 So, for 1/2 + 2/5, you would want to make sure they both have 10 as the denominator, representing them as 5/10 + 4/10, so you can then add the numerators and get 9/10.因此,对于 1/2 + 2/5,您需要确保它们都以 10 作为分母,将它们表示为 5/10 + 4/10,这样您就可以将分子相加得到 9/10。

Here's how you might want to do it in Java:以下是您可能希望在 Java 中执行此操作的方式:

numeratorFirst = numeratorFirst * denominatorSecond;
numeratorSecond = numeratorSecond * denominatorFirst;
denominatorTotal = denominatorSecond * denominatorFirst;
numeratorTotal = numeratorFirst + numeratorSecond;

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

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