如何将小数转换为分数? [英] How to convert decimal to fractions?
本文介绍了如何将小数转换为分数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将小数转换为分数.转换成10英尺很容易.
What I need to convert decimal to fractions. It is easy to convert to 10's feet.
1.5 => 15/10
这可以通过以下代码完成:
This can do via this code:
public class Rational {
private int num, denom;
public Rational(double d) {
String s = String.valueOf(d);
int digitsDec = s.length() - 1 - s.indexOf('.');
int denom = 1;
for (int i = 0; i < digitsDec; i++) {
d *= 10;
denom *= 10;
}
int num = (int) Math.round(d);
this.num = num;
this.denom = denom;
}
public Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
public String toString() {
return String.valueOf(num) + "/" + String.valueOf(denom);
}
public static void main(String[] args) {
System.out.println(new Rational(1.5));
}
}
但是我想要的是
1.5 => 3/2
,我不知道如何进行. 我的问题不是重复.因为其他相关问题是C#.这是java.
and I don't get how to proceed. My question is not a duplication. Because other related question is C#. This is java.
推荐答案
您应该找到结果数字的最大公约数,并将分子和分母除以它.
You should find the greatest common divisor of the resulted numbers and divide the numerator and denominator by it.
这是一种实现方法:
public class Rational {
private int num, denom;
public Rational(double d) {
String s = String.valueOf(d);
int digitsDec = s.length() - 1 - s.indexOf('.');
int denom = 1;
for (int i = 0; i < digitsDec; i++) {
d *= 10;
denom *= 10;
}
int num = (int) Math.round(d);
int g = gcd(num, denom);
this.num = num / g;
this.denom = denom /g;
}
public Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
public String toString() {
return String.valueOf(num) + "/" + String.valueOf(denom);
}
public static int gcd(int num, int denom) {
....
}
public static void main(String[] args) {
System.out.println(new Rational(1.5));
}
}
这篇关于如何将小数转换为分数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文