我正在尝试制作一个将值转换为位的程序。一切正常,直到我达到GB(千兆字节)。因此,例如1 GB应该等于80亿位,但结果却给了我一个否定的答案。这是我的代码,有人可以给我一些启示吗?
else if(line.equals("GB")) {
Scanner num = new Scanner(System.in);
System.out.println("How many GigaBytes are you transfering to bits?");
int number = num.nextInt();
//int ans = number * 8 * 1000000000;
BigInteger bigAns = BigInteger.valueOf(number * 8 * 1000000000);
System.out.println(number + " GigaByte(s) equals " + bigAns + " bits.");
}
这是我得到的输出:1 GigaByte等于-589934592位。
BigInteger
在整个计算过程中使用它并不是一件坏事。这样,您在将这些数字相乘时就不会冒溢出的风险。
BigInteger bigAns = BigInteger.valueOf(number).multiply(BigInteger.valueOf(8))
.multiply(BigInteger.valueOf(1000000000L));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句