添加分数 (Java)
Adding Fractions (Java)
在这个程序中,要求用户输入代表两个分数的 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”部分。
要得到两个分数的总和 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);
虽然这不会简化为分数的最简单形式。
在这个程序中,要求用户输入代表两个分数的 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”部分。
要得到两个分数的总和 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);
虽然这不会简化为分数的最简单形式。