我输入的分数总是返回0



可能重复:
Java中的除法总是导致零(0(?

所以我正在写这个程序,我觉得它很好。GUI窗口弹出,我输入了一个分子和一个恶魔。但无论我输入什么,它总是说它等于0。因此,如果我为分子输入2,为恶魔输入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;
}
}

在类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.
}

相关内容

  • 没有找到相关文章

最新更新