如何将此代码的结果转换为小数? [英] How do I convert the result of this code into a decimal?

查看:71
本文介绍了如何将此代码的结果转换为小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个计算器,它将分数加在一起,所以我已经完成了,但不是给了我另一个分数而是给了我一个小数。



我尝试过:



公共类AddFractions扩展ConsoleProgram

{

public void run()

{

double numeratorA = readInt(第一部分的分子是什么?);

double denominatorA = readInt(第一部分的分母是什么?);

double numeratorB = readInt(第二部分的分子是什么?);

double denominatorB = readInt(第二部分的分母是什么?);

double Sum = numeratorA / denominatorA * denominatorB / numeratorB;

系统.out.println(总和);

}

}

解决方案

你应该单独计算结果的分子和denomiator:

n = n1 * d2 + n2 * d1

d = d1 * d2

然后(可选)找到他们的 GCD 以简化分数。


< blockquote class =quote>

引用:

我正在尝试编写一个计算器,它会将分数加在一起,所以我已经完成了它,但不是给了我另一个分数它给我一个小数代替。



你已经知道你不能将用户输入存储为 double 变量。你使用的是2个变量。

是什么让你认为你可以用计算结果来做?


I am trying to write a calculator where it adds fractions together, and so I have done it, but instead of giving me back another fraction it gives me a decimal instead.

What I have tried:

public class AddFractions extends ConsoleProgram
{
public void run()
{
double numeratorA = readInt("What is the numerator of the first fraction? ");
double denominatorA = readInt("What is the denominator of the first fraction? ");
double numeratorB = readInt("What is the numerator of the second fraction? ");
double denominatorB = readInt("What is the denominator of the second fraction? ");
double Sum = numeratorA/denominatorA * denominatorB/numeratorB;
System.out.println(Sum);
}
}

解决方案

You should separately compute the numerator and denomiator of the result:
n = n1*d2 + n2*d1
d = d1*d2
and then (optionally) find their GCD in order to simplify the fraction.


Quote:

I am trying to write a calculator where it adds fractions together, and so I have done it, but instead of giving me back another fraction it gives me a decimal instead.


You already have the knowledge that you can't store the user input as a fraction in a double variable. You are using 2 variables.
What make you think that you can do it with the result of a calculation ?


这篇关于如何将此代码的结果转换为小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆