【发布时间】:2017-10-02 21:44:08
【问题描述】:
下面的代码要求用户输入一个数字,然后将每个数字相加得到总和。例如,如果我输入 123,它将执行 (1+2+3),然后输出 6。我有递归方法: public static int sumDigits(long n) 但是我不确定它何时被调用或它是如何工作的,long n 声明是什么意思?
//this is my code
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a integer: ");
long n = input.nextLong();
// Display the sum of all the digits in the integer
System.out.println("The sum is: " + sumDigits(n));
}
//recrusve method that computes the sum of the digits in an integer
public static int sumDigits(long n) {
int sum = 0;
while (n > 0)
{
sum += n % 10;
n /= 10;
}
return sum;
}
}
【问题讨论】:
-
递归函数是调用自身的函数。
sumDigits因此不是递归函数。 -
您的代码中没有递归。如果您无法理解 long n 的含义,那么您将很难理解递归。
-
显然你的问题与
oracle无关。请查看 StackOverflow 网站添加到您的帖子中的标签,并根据需要进行编辑。这次为你做。 -
你不应该问
long n是什么意思。如果您可以访问 StackOverflow,我几乎可以肯定您也可以访问 Google。搜索一个有意义的短语,我尝试了“Java long data type”——它返回的第一个链接是这样的:docs.oracle.com/javase/tutorial/java/nutsandbolts/… 然后,习惯阅读文档——它会为你节省很多时间。 -
这里没有明确的问题。也许您应该弄清楚如何将 sumdigits 函数重写为递归函数?听起来您需要更加熟悉基础知识才能解决这个问题。
标签: java recursion methods jgrasp