可能重複:
Division in Java always results in zero (0)?我輸入的分數總是返回0?
所以我在寫這個程序,我認爲這是很好的。 GUI窗口彈出,我輸入了一個分子和一個demoninator。但是無論我輸入什麼,它總是說它等於0.所以如果我爲分子輸入2,爲demoninator輸入3,輸出將是2/3 = 0.問題是什麼?
我改變了「INT月」,以「雙減少」,如下圖所示,把「this.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;
}
}
難道他們不教在實驗室測試和調試? – Jayan