可能重复:
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;
}
}