添加分数(Java)

问题描述 投票:-3回答:1

在此程序中,要求用户输入代表两个分数的4个整数。

[先要求分子的分母,然后是分母。然后要求第二个的分子和分母。

程序应将两个分数相加并打印出来结果。

我不知道如何将这些分数相加

public class AddFractions extends ConsoleProgram
{
    public void run()
    {
        int nffraction = readInt("What is the numerator of the first fraction?: ");
        int dffraction = readInt("What is the denominator of the first fraction?: ");
        int nsfraction = readInt("What is the numerator of the second fraction?: ");
        int dsfraction = readInt("What is the denominator of the second fraction?: ");
        int sum = 
        System.out.print(nffraction + "/" + dffraction + " + " + nsfraction + "/" + dsfraction + "=" + sum);
    }
}

这是预期的输出“ 1/2 + 2/5 = 9/10”,但我无法弄清楚“ = 9/10”部分。

java fractions
1个回答
0
投票

要获得两个符号a/b + c/d的总和,您需要执行(a*d + c*b)/b*d

因此,您的示例:

int numerator = (nffraction * dsfraction + nsfraction * dffraction)
int denominator = dsfraction * dsfraction
System.out.print(nffraction + "/" + dffraction + " + " + 
nsfraction + "/" + dsfraction + "=" + numerator + "/" + denominator);

尽管这不会简化为分数的最简单形式。

© www.soinside.com 2019 - 2024. All rights reserved.