我需要一些帮助来检查我的程序以找到数字根。如果用户输入5635,则数字根为1.要查找数字的数字根,请在数字5 + 6 + 3 + 5中添加所有数字,然后得到结果19.然后添加结果1 + 9 = 10.然后你加1 + 0直到得到1是你的数字根。
import acm.program.*;
public class DigitRoot extends ConsoleProgram {
public void run() {
println("this program attemts to find the digit root a user enters.");
int n = readInt("please enter any positive integer: ");
int dsum = 0;
int sumtotal = 0;
int threesum = 0;
int foursum = 0;
while (n > 0) {
dsum += n % 10;
n /= 10;
if (dsum > 9) {
sumtotal = (dsum / 10) + (dsum % 10);
} else if (sumtotal > 9) {
threesum = (sumtotal / 10) + (sumtotal % 10);
} else if (threesum > 9) {
foursum = (threesum / 10) + (threesum % 10);
} else if (foursum < 9) {
println("your digit root is" + foursum);
} else {
println("this program is borken.");
}
}
}
}
答案 0 :(得分:2)
有些数学告诉你,这只是除以9时的余数(我们将0的余数替换为9)。以下适用于n > 0
:
int root = n % 9;
if (root == 0) root = 9;
答案 1 :(得分:2)
试试这个
int n = 5635;
int total = 0;
do {
while (n > 0) {
total = total + (n % 10);
n = (n / 10);
}
n = total;
total = 0;
} while (n > 9);
System.out.println(n);
或使用递归,
int n = 5635;
int total = 0;
do {
total = Test.sumofdigit(n);
n = total;
} while (total >= 10);
System.out.println(total);
public static int sumofdigit(int inputnumber) {
if (inputnumber < 10)
return inputnumber;
return sumofdigit(inputnumber / 10) + inputnumber % 10;
}
答案 2 :(得分:1)
你的逻辑似乎很复杂。试试这个
while ( n > 0 ) {
dsum += n % 10;
n /= 10;
if(n==0 && dsum >9){
n=dsum;
dsum =0;
}
}
System.out.println(dsum);
答案 3 :(得分:0)
使用递归的示例 - 我使用字符串计算数字的总和:它不是很有效但是(稍微)更容易。在循环中使用n % 10
可以随意改进。
public static void main(String[] args) throws Exception {
System.out.println(calculateRoot(5635)); //prints 1
}
public static int calculateRoot(int n) {
int sum = sumFigures(n);
return sum < 10 ? sum : calculateRoot(sum);
}
public static int sumFigures(int n) {
String s = String.valueOf(n);
int sum = 0;
for (char c : s.toCharArray()) {
sum += c - '0';
}
return sum;
}
答案 4 :(得分:0)
玩角色怎么样?
@Test
public void testGetRoot(){
int n=3565;
char[] chars;
while (n>9){
int r=0;
chars = String.valueOf(n).toCharArray();
for(char c : chars)r+=(c-'0');
n=r;
}
System.out.println(n);
}
这将输出1。
答案 5 :(得分:0)
这是另一个答案中嵌套循环解决方案的双功能版本,可能更容易理解:
int digitRoot(int num) {
// calculate digit root as specified:
// get sum of digits until there is only one digit, which is the root
while (num > 9) {
num = sumOfDigits(num);
}
return num;
}
int sumOfDigits(int num) {
int sum = 0;
// negative numbers not supported, for them 0 is returned...
while (num > 0) {
sum += num % 10; // add least significant digit's value to sum
num /= 10; // remove the least significant digit from num
}
return sum;
}