我需要一些帮助来检查我的程序以找到数字根。如果用户输入 5635,则数字根为 1。要查找数字的数字根,请将数字 5 + 6 + 3 + 5 中的所有数字相加,得到结果 19。然后将结果相加 1 + 9 = 10。然后添加 1 + 0 直到得到 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.");
}
}
}
}
最佳答案
一些数学告诉你,这只是除以 9 时的余数(我们用 9 替换 0 的余数)。以下适用于 n > 0
:
int root = n % 9;
if (root == 0) root = 9;
关于java - 求数字根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14559305/