![](/img/trans.png)
[英]return value from recursive method in java when returning math expresion
[英]Return value from recursive method (java)
我必須編寫一個遞歸方法來對整數進行求和。
該方法工作正常,但我不明白為什么它返回最后一個整數而不是總數。
import java.util.Scanner;
public class SommaCifreRicorsivo{
public static void main (String[] args){
System.out.printf("Inserire un numero: ");
Scanner tastiera = new Scanner(System.in);
int numero = tastiera.nextInt();
int somma = 0;
int risultato = eseguiSomma(numero,somma);
System.out.println("La somma delle sue cifre è " + risultato);
}
public static int eseguiSomma(int numero, int somma){
//Caso base
if (numero < 10) {
somma = somma + numero;
System.out.println("Aggiungo la cifra " + numero + " alla somma, ottenendo " + somma);
return (somma += numero);
}
//Chiamate ricorsive
somma = somma + numero%10;
System.out.println("Aggiungo la cifra " + (numero%10) + " alla somma, ottenendo " + somma);
eseguiSomma((numero/10), somma);
return somma;
}
}
somma
是基本類型( int
),因此Java按值傳遞它。 這意味着您要修改的值只是存儲在每個遞歸調用的堆棧幀中的somma
的副本 ,而不是最終的返回值。
因此, somma
這個論點是完全沒有必要的。 相反,您應該返回遞歸調用的返回值加上新的數字。 這提供了一個簡單得多的解決方案。
public static int eseguiSomma(int numero){
//Caso base
if (numero < 10) {
return numero;
}
//Chiamate ricorsive
return numero % 10 + eseguiSomma(numero / 10);
}
// now simply call without somma
int risultato = eseguiSomma(numero);
只需將其更正為:
import java.util.Scanner;
public class SommaCifreRicorsivo{
public static void main (String[] args){
System.out.printf("Inserire un numero: ");
Scanner tastiera = new Scanner(System.in);
int numero = tastiera.nextInt();
int somma = 0;
int risultato = eseguiSomma(numero,somma);
System.out.println("La somma delle sue cifre è " + risultato);
}
public static int eseguiSomma(int numero, int somma){
//Caso base
if (numero < 10) {
somma = somma + numero;
System.out.println("Aggiungo la cifra " + numero + " alla somma, ottenendo " + somma);
return (somma += numero);
}
//Chiamate ricorsive
somma = somma + numero%10;
System.out.println("Aggiungo la cifra " + (numero%10) + " alla somma, ottenendo " + somma);
// the error was on this line!
somma += eseguiSomma((numero/10), somma);
return somma;
}
}
您正在嘗試修改somma,但是somma是原始類型,因此您只能修改其本地副本,並且somma保持不變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.