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;
}
}
4

1 に答える 1

3

クラスRationaldecは、 は初期化されていないため、デフォルトで 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.
}
于 2013-01-19T02:32:16.403 に答える