我输入的分数总是返回0?

时间:2013-01-19 02:30:41

标签: java class rational-number

  

可能重复:
  Division in Java always results in zero (0)?

所以我正在编写这个程序,我认为这很好。弹出GUI窗口,我输入了一个分子和一个演示者。但无论我输入什么,它总是说它等于0.所以如果我为分子输入2和为Demoninator输入3,那么输出将是2/3 = 0.问题是什么?

我将“int dec”更改为“double dec”,如下所示,并将“this.dec = dec”放在Rational类下,但这并没有解决任何问题

import javax.swing.JOptionPane;


public class lab8
{
public static void main (String args[])
{
    String strNbr1 = JOptionPane.showInputDialog("Enter Numerator ");
    String strNbr2 = JOptionPane.showInputDialog("Enter Denominator ");

    int num = Integer.parseInt(strNbr1);
    int den = Integer.parseInt(strNbr2);

    Rational r = new Rational(num,den);
    JOptionPane.showMessageDialog(null,r.getNum()+"/"+r.getDen()+" equals "+r.getDecimal());

    System.exit(0);
}
}



class Rational
{
private int num;
private int den;
private double dec;

public Rational(int num, int den){
 this.num = num;
 this.den = den;
 this.dec = dec;
}
public int getNum()
{
    return num;
}

public int getDen()
{
    return den;
}

public double getDecimal()
{
    return dec;
}

private int getGCF(int n1,int n2)
{
    int rem = 0;
    int gcf = 0;
    do
    {
        rem = n1 % n2;
        if (rem == 0)
            gcf = n2;
        else
        {
            n1 = n2;
            n2 = rem;
        }
    }
    while (rem != 0);
    return gcf;
}
}

1 个答案:

答案 0 :(得分:3)

在课程Rational中,dec未初始化,因此默认为0.因此,当您稍后调用getDecimal()时,它始终返回0.

public Rational(int num, int den){
  this.num = num;
  this.den = den;

  // TODO: initialize dec here, otherwise it is implicitly set to 0.
}