DRoot dRoot = new DRoot();
System.out.println("Answer from main : " + dRoot.digital_root(493193));
数字根是数字中所有数字的递归总和。给定n,取n的数字之和。如果该值有两位数字,则继续以这种方式减少直到产生一位数字。这只适用于自然数。试图通过if/else返回一个值
public class DRoot {
public static int digital_root(int num)
{
String temp = Integer.toString(num);
int a[] = new int[temp.length()];
int output = 0;
for(int i = 0; i < temp.length(); i++) //getting individual numbers from passed in integer
{
a[i] = Integer.parseInt(temp.substring(i, i+1));
}
for (int i = 0; i < a.length; i++) //sum of all digits in the number
{
output += a[i];
}
if(String.valueOf(output).length() != 1)
{
digital_root(output);
} else {
return output;
}
return 0;
}
}
正如你可以在上面看到,我试图通过测试“如果输出的值不等于1,则返回digital_root(output);
”但是一个if else语句返回一个数字,这回没有按” t工作,而是从返回下面的返回0,我放在那里清除返回错误。任何帮助解决这个问题?感谢