gpt4 book ai didi

java - 我输入的分数总是返回 0?

转载 作者:行者123 更新时间:2023-12-02 00:03:16 25 4
gpt4 key购买 nike

Possible Duplicate:
Division in Java always results in zero (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.
}

关于java - 我输入的分数总是返回 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14410556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com