2017-08-05 142 views
1

我寫了一個以int爲參數的遞歸函數,並返回BigInteger。沒有什麼似乎是錯的,但是一行以紅色標出。遞歸函數返回類型錯誤

我很抱歉,如果這是如此明顯,但目前我不能包裹我的頭。

public static BigInteger factorial(int a){ 
     BigInteger tot=BigInteger.valueOf(a); 
     if(a>1)tot*=factorial(a-1); 
     return tot; 
    } 

if(a>1)tot*=(factorial(a-1));用紅色下劃線。

錯誤:

Required:BigInteger, Found:int

同時:

public static void main(String[] args) { 
    BigInteger a=f(8); 
} 

public static BigInteger f(int a){ 
    BigInteger g=BigInteger.valueOf(a); 
    return g; 
} 

...作品。

它來自Intellij Idea。是否有一些基本和重要的概念,我錯過了?謝謝。

編輯:所以答案,爲用戶clebe45解釋,是Java 不支持操作符重載,不像C++,這是我比較熟悉。如果任何人發現這是重複的,請刪除,我提供我的道歉。

+1

上'BigInteger's必須與相應的[類方法]來完成(https://docs.oracle.com/javase/7/docs/api/java所有基本的數學運算/math/BigInteger.html) – Isac

回答

2

Java不支持操作符重載,所以你不能用乘法*操作就可以了。相反,你應該使用:

public BigInteger multiply(BigInteger val)

1

*=不適用於BigInteger。使用multiply代替:

if (a > 1) tot = tot.multiply(factorial(a - 1));