2013-01-19 24 views
0

可能重複:
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; 
} 
} 
+0

難道他們不教在實驗室測試和調試? – Jayan

回答

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. 
} 
+1

也是'int'。 –

+1

和'getDecimal'返回一個'int' –

+0

我把class.dec = dec放在Rational類中,但它沒有修復任何東西 – user1991954