java 用java简化分数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6882618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:43:32  来源:igfitidea点击:

Simplifying Fractions With java

javanumbersrational-numberfractions

提问by user759630

Hey guys I am working on a SW here I am kinda in need of help, you see we need to make a method where we are gonna simplify fractions. any idea how? here's my code as of now (don't mind the dvalue Method it is already finsih all I need is the simplify method)

嘿伙计们,我正在这里开发软件,我有点需要帮助,你看我们需要制定一种方法来简化分数。知道怎么做吗?这是我现在的代码(不要介意 dvalue 方法,它已经完成了,我只需要简化方法)

public class Fraction {

    public int num;
    public int den;
    public double dValue;

    public void display()
    {
        System.out.println("Numerator: "+num);
        System.out.println("Denominator: "+den);
    }

    public double dValue()
    {
        dValue = (double)num/den;
        return dValue;
    }


}


public class FractionTest {

        public static void main(String args[])
        {
            Fraction f = new Fraction();
            f.num = 50;
            f.den = 100;
            f.display();

            double d = f.dValue();
            System.out.println(d);
        }   
}

回答by yosh kemu

Simplifying fractions is easy if you can folow the steps:

如果您可以遵循以下步骤,则简化分数很容易:

  1. find gcd of both num and den, so you have gcd=GCDFind(gcd, num);
  2. now, if gcd==1, then the fraction cannot be simplified (it is already in simplified form).
  3. if gcd > 1, then newNum = num/gcd; and newDen = den/gcd;
  1. 找到 num 和 den 的 gcd,所以你有 gcd=GCDFind(gcd, num);
  2. 现在,如果 gcd==1,那么分数不能被简化(它已经是简化形式了)。
  3. 如果 gcd > 1,则 newNum = num/gcd;和 newDen = den/gcd;

It's all you need I think.

我想这就是你所需要的。

The gcd stands for Greates Common Divisor... Code easily findable, and I just googled JavaScript implentation working this way in few seconds: http://www.calculla.com/en/fraction

gcd 代表 Greates Common Divisor ......代码很容易找到,我只是在几秒钟内用谷歌搜索了 JavaScript 实现:http: //www.calculla.com/en/fraction