二元运算符的错误操作数类型。第一种:BigInteger 第二种:BigInteger

问题描述 投票:0回答:1

所以我有一个使用 3 个变量(

i
factorial
number
)并返回
BigInteger
的方法。
number
i
int
s 和
factorial
BigInteger
。在我的方法中,我有一个 for 循环,如下所示

public static BigInteger bigIntegerFactorialMethod(int number){
    int i =  1;
    BigInteger factorial = BigInteger.valueOf(1);
  
    for(i = 1; i <= number; i++){
        factorial = factorial * BigInteger.valueOf(i);
        i++;
    }
  
    return factorial;
}

在第六行,我得到这个问题的标题是在 for 循环中更新阶乘的错误。

二元运算符“*”的错误操作数类型。第一种:

BigInteger
第二种:
BigInteger
"

我猜是因为我没有比较对象的正确属性,系统不知道要比较什么?

java
1个回答
0
投票

不能使用“*”运算符来乘以对象。 另外,我看到您将变量“i”增加了两次(在 for 和循环体中)。

它可能看起来像这样:

public static BigInteger bigIntegerFactorialMethod(int number) {
    BigInteger factorial = BigInteger.valueOf(1);

    // here we start from 2 because we already have '1'
    for (int i = 2; i <= number; i++) {
        factorial = factorial.multiply(BigInteger.valueOf(i));
    }

    return factorial;
}
© www.soinside.com 2019 - 2024. All rights reserved.