java - 寻找数字的数字根

标签 java math

研究问题是找到一个已经提供的数字的数字根。老师给我们提供了数字 2638。为了找到数字的根,你必须将每个数字分别相加 2 + 6 + 3 + 8 = 19。然后你取结果 19 并将这两个数字相加 1 + 9 = 10 . 再次做同样的事情 1 + 0 = 1. 数位根是 1.

我的第一步是使用变量 total 将数字 2638 相加得到总数 19。然后我尝试使用第二个 while 循环通过使用 %

我必须尝试使用​​基本整数运算(+、-、*、/)来解决问题。
1.是否有必要和/或可能使用嵌套while循环来解决问题?
2.我的数学正确吗?
3. 正如我在这里写的那样,它不在 Eclipse 中运行。我是否正确使用了 while 循环?

import acm.program.*;


public class Ch4Q7 extends ConsoleProgram {
   public void run(){
      println("This program attempts to find the digit root of your number: ");

      int n = readInt("Please enter your number: "); 

      int total = 0;

      int root = total;


      while (n > 0 ){
        total = total + (n %10);
    n = (n / 10);

    }   

   while ( total > 0 ){
     root = total; 
     total = ((total % 10) + total / 10); 
    }


     println("your root should be " + root);
}

}

最佳答案

我认为它确实可以运行,但有点太多了:-)

total = ((total % 10) + total / 10); 

不能收敛到 0。另外,你的程序只能处理非常特殊的情况。正如其他人指出的那样,这可以递归解决,但也可以只用一个双循环。像您尝试的一系列循环将不起作用。

试试这个(输入变量与程序中的相同,它实际上是两个循环的插件替代品):

    do {
        while (n > 0) {
            total = total + (n % 10);
            n = (n / 10);
        }
        n = total;
        total = 0;
    } while (n > 9);  // need at least 1 more loop

此循环后 n 将包含根数。

关于java - 寻找数字的数字根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13043939/

相关文章:

java - @ControllerAdvice 仅用于集中/全局异常处理或我们可以用它做的任何其他事情?

Java: 包 R 不存在

math - Perlin 噪声不同的实现

c++ - 四舍五入一个整数,使其乘以一个 float 返回一个整数

java - 从互联网保存 Excel 文件

java - 不知道如何修复我的代码

java - 如何使用 JUnit 测试 Java Web 服务?

regex - 正则表达式以匹配不可约分数

math - 用于多元线性回归的纯 python 代码

python - 用于打印数字除数乘积的高效 python 代码