可能重复: BigInteger的困难性
import java.math.BigInteger;
public class KillerCode{
public static void main(String[]args){
BigInteger sum=null;
for(int i=1;i<=1000;i++){
sum=sum+Math.pow(i, i);
System.out.println(sum);
}
}
} 当我试图运行此代码时,会出现以下错误消息。
对于参数类型BigInteger,double,运算符+未定义。
我怎么才能解决这个问题?谢谢。
发布于 2012-10-15 03:22:46
不能在BigIntegers中使用典型的数学运算符,请检查此处http://docs.oracle.com/javase/6/docs/api/java/math/BigInteger.html
您需要使用BigInteger.add(your numbers here)
进一步解释,
sum = sum.add(new BigInteger(i).pow(i));发布于 2012-10-15 03:25:20
您不能这样做,因为sum不是一个整数,而是对一个对象的引用。
与C++不同,java不允许操作符重载,因此需要使用类方法来执行操作。
发布于 2012-10-15 04:39:08
sum初始化为有意义的非null值(当前初始化为null):
BigInteger和= BigInteger.ZERO;
否则的话
和=sum.add(.)
没有意义(除非你想要一个NullPointerException)。BigInteger.valueOf(long)将整数值映射到BigInteger。
不要使用表达式new BigInteger(i)。new BigInteger(i)调用的构造函数是BigInteger(byte[]),对于大于255的值(您有.)有错误的结果(为了您的目的)。BigInteger.add(BigInteger)。BigInteger.pow(int)而不是Math.pow(int,int);由于您正在执行(大)整数运算,所以避免将您的工作映射到浮点世界,即double或float,否则您将失去BigInteger的优势。https://stackoverflow.com/questions/12888848
复制相似问题