如何对对象进行算术运算

Jon*_*Lam -1 java math

BigInteger在两个简单的java文件中有几个对象.但是,由于它们不是原始类型,因此算术运算符不会对它们起作用.

每次使用运算符时都会出错,如下所示:

.\_Mathematics\Formulas\Factorial.java:10: error: bad operand types for binary o
perator '*'
                        result *= i;
                               ^
  first type:  BigInteger
  second type: int
Run Code Online (Sandbox Code Playgroud)

他们来了:

package _Mathematics.Formulas;
import java.math.*;

public class Factorial<T extends Number> {
    public T o;
    public BigInteger r;
    public Factorial(int num) {
        BigInteger result = new BigInteger("1");
        for(int i = num; i > 0; i--)
            result *= i;
        this.o = num;
        this.r = result;
    }
} 
Run Code Online (Sandbox Code Playgroud)

package _Mathematics.Formulas;
import java.math.*;

public class Power<T extends Number> {
    public T o;
    public BigInteger r;
    public Power(T num, int pow) {
        BigInteger result = new BigInteger(1);
        for(int i = 0; i < pow; i++) {
            result *= num;
        }
        this.o = num;
        this.r = result;
    }
}
Run Code Online (Sandbox Code Playgroud)

我四处寻找如何解决这个问题,但我找不到答案.

有人可以帮我这个吗?

谢谢.

Rei*_*eus 10

BigInteger有这方面的运算符方法.由于BigInteger它本身是不可变的,因此需要将值赋给结果

例如以下内容

result *= num;
Run Code Online (Sandbox Code Playgroud)

会变成

result = result.multiply(num);
Run Code Online (Sandbox Code Playgroud)