java 分数,使用Java简化分数

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)

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);

}

}

解决方案

Simplifying fractions is easy if you can folow the steps:

find gcd of both num and den, so you have gcd=GCDFind(gcd, num);

now, if gcd==1, then the fraction cannot be simplified (it is already in simplified form).

if gcd > 1, then newNum = num/gcd; and 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值