我必須使用遞歸找到不能被7整除的所有偶數的和。我想這個代碼,但它似乎我犯錯誤的地方,因爲它返回0:Java遞歸不可被特定數字整除的數字
public static void main(String[] args) {
System.out.println(specialSum(50));
}
public static int specialSum(int a) {
if ((a >= 1) && ((specialSum(a-1))%7 !=0)) {
return a + specialSum(a -1);
} else{
return 0;
}
}
}
那麼,遞歸意味着你繼續迭代,直到你達到最終狀態。這個條件是你的'else',然後你只返回0.你可能想要傳遞當前的總和到方法中。 –
@ChrisWohlert沒有必要將當前總和傳遞給方法。檢查我的解決方案 – Zinov