Java-数字的递归和及其工作方式 [英] Java - Recursion sum of number and how it work
本文介绍了Java-数字的递归和及其工作方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个递归函数,例如,当我用数字5调用时,该函数将计算5的所有数字之和.1 + 2 + 3 + 4 + 5 = 15
I am trying to write a recursive function that when I call with number 5 for example then the function will calculate the sum of all digits of five. 1 + 2 + 3 + 4 + 5 = 15
当前代码总是返回0,每次n的金额如何?
The current code always returns 0, how can the amount each time the n?
public class t {
public static void main(String[] args) {
System.out.println(num(5));
}
public static int num(int n) {
int sum = 0;
sum += n;
if (n == 0)
return sum;
return num(n - 1);
}
}
谢谢.
推荐答案
您可以-
而不是将总和设置为 0
这样做:
public int sumUp(int n){
if (n==1)
return 1;
else
return sumUp(n-1)+n;
}
这篇关于Java-数字的递归和及其工作方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文