划分(6.022 / 6.022 = 1000)Java时获得1000作为答案而不是1

时间:2014-02-22 10:21:31

标签: java integer-division

所以,我是编程的新手,我试图制作一个基本的鼹鼠(化学)计算器只是为了好玩。我没有找到这个问题。如果有人回答,请将链接发给我。

这是公式:n = N / Na其中n = moleNa = 6.022E23

代码的第一部分抛出错误。只是试图得到一个,用我的给定N除以Na,甚至用6.022而不是6.022E23我得到1000.0作为答案。

Scanner in = new Scanner(System.in);
double Na = 6.022;

System.out.print("What do you want to know? Mol(0) or N(1)? ");
int first = in.nextInt();
if (first == 0){
    System.out.print("Insert N: ");
    double N = in.nextDouble();
    double mol = N/Na;
    System.out.print("There are " + mol + " mol in that sample.");
}
else if (first == 1){
    System.out.print("Insert mol: ");
    double mol = in.nextDouble();
    double N = mol*Na;
    System.out.print("There are " + N + " molecules, atoms or ions in that sample.");   
}

输出0:

What do you want to know? Mol(0) or N(1)? 0  
Insert N: 6.022  
There are 1000.0 mol in that sample.  

输出1:

What do you want to know? Mol(0) or N(1)? 1  
Insert mol: 1  
There are 6.022 molecules, atoms or ions in that sample.  

提前致谢。

1 个答案:

答案 0 :(得分:5)

由于您正在编写一个小代码,因此对我可以制作的新编码器的简单建议是硬编码所以它是:

double mol = N/6.022;

这可以满足您的需求。错误是因为它正在识别它,因为它将其视为6022而不是6.022。作为千元指标。希望这会有所帮助。

如果您不想对值进行硬编码,请添加:

in.useLocale(Locale.US);

在您声明扫描仪的正下方。这两种解决方案都可以解决您的问题。