[英]My java program will not return the correct value?
I have written a java program that finds the recursive sum of the digits of a number.我编写了一个 java 程序,它可以找到一个数字的数字的递归和。
It prints the correct value in the line right before the return statement, but still returns the wrong value.它在 return 语句之前的行中打印正确的值,但仍然返回错误的值。
public class DRoot {
public static int digital_root(int n) {
//going to solve using recursion
System.out.println(n + " before if and for loop");
String temporary = Integer.toString(n);
int tempInteger = n;
System.out.println(temporary.length() + " is temporary length");
if(temporary.length() == 1){
System.out.println("returns at beginning");
System.out.println("n before return is: " + n);
return tempInteger;
}
n = 0;
if(temporary.length() != 1){
for(int i = 0; i < temporary.length(); i ++){
n += Integer.parseInt(temporary.substring(i, i+1));
System.out.println(n + " during if and for loop");
}
} else {
System.out.println("returns after for loop");
return n;
}
//calls the digital_root method recursively
digital_root(n);
return n;
}
}
The result of your recursive call is lost.递归调用的结果丢失了。 Maybe what you want is:
也许你想要的是:
n = digital_root(n);
return n;
Your code could have been much shorter and simpler.您的代码本可以更短更简单。
Based on your attempts, perhaps it would be best to represent the number as a String
.根据您的尝试,也许最好将数字表示为
String
。
At each step of the recursion, take the first digit and add it to the sum of the sub-string without the first digit.在递归的每个步骤中,取第一个数字并将其添加到没有第一个数字的子字符串的总和中。 Once you run out of digits, you stop.
一旦你用完数字,你就停下来。
Something like this:像这样的东西:
public class DRoot {
public static int recursiveDigitSum(String n) {
if (n.length() == 0) {
return 0;
}
return n.charAt(0) - '0' + recursiveDigitSum(n.substring(1));
}
public static void main(String[] args) {
System.out.println(recursiveDigitSum("51")); // outputs 6
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.