1
  public static void gramstoAtoms()
  {
   System.out.println("Enter Amount of grams");
   Scanner keyboard = new Scanner(System.in);
   long x = keyboard.nextLong();
   System.out.println("Enter Unit Grams");
   long y = keyboard.nextLong();
   long result = x/y;
   long answer = result*60200000000000000000000;
   System.out.println(answer + "Atoms");
  }

如何更改此代码,以免出现整数太长错误?

4

4 回答 4

7

只需使用 BigInteger 而不是 long

BigInteger bi=new BigInteger("6020000000000000000000");

对于您的方法:

public static void gramstoAtoms()
  {
   System.out.println("Enter Amount of grams");
   Scanner keyboard = new Scanner(System.in);
   String x = keyboard.nextLine();
   System.out.println("Enter Unit Grams");
   String y = keyboard.nextLine();
   BigInteger result = new BigInteger(x).divide(new BigInteger(y));
   BigInteger answer = result.multiply(new BigInteger("60200000000000000000000"));
   System.out.println(answer + "Atoms");
  }

如果你的xandy很小,你可以用简单的 long 来使用它们,但是当乘以 602.......0000 时,使用BigInteger

于 2013-05-09T13:00:55.637 回答
3

如果我没记错的话,阿伏伽德罗的数字是6.02e24。Along的最大值为9,223,372,036,854,775,807,但不够大。你需要BigInteger.

于 2013-05-09T13:01:01.437 回答
1

这是一个没有的解决方案BigInteger

long answer = result * 602;
System.out.println(answer + "00000000000000000000Atoms");
于 2013-05-09T13:13:07.623 回答
0

Dima Goltsman 是正确的,您必须使用 BigInteger 修复它

于 2013-05-09T13:21:49.710 回答