[英]Getting 1000 as an answer instead of 1 when dividing (6.022/6.022=1000) Java
所以,我是編程的新手,我試圖制作一個基本的鼴鼠(化學)計算器只是為了好玩。 我沒有找到這個問題。 如果有人回答,請發給我鏈接。
這是下式: n = N / Na
,其中n = mole
, Na = 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.
提前致謝。
既然你正在編寫一個小代碼,那么對於我可以制作的新編碼器的簡單建議就是硬代碼,所以它是:
double mol = N/6.022;
這給你你想要的。 錯誤是因為它正在識別它,因為它將其視為6022而不是6.022。 作為千元指標。 希望這可以幫助。
如果您不想對值進行硬編碼,請添加:
in.useLocale(Locale.US);
在您聲明掃描儀的下方。 這兩種解決方案都可以解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.