在'while'循环之后我不理解这段代码的逻辑,我知道阿姆斯特朗的概念。 [英] I'm not understanding the logic of this code after the 'while' loop, I know the concept of armstrong no.

查看:87
本文介绍了在'while'循环之后我不理解这段代码的逻辑,我知道阿姆斯特朗的概念。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class ArmstrongNumber
{
   public static void main(String args[])
   {
      int n, sum = 0, temp, r;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter a number to check if it is an armstrong number");
      n = in.nextInt();

      temp = n;

      while( temp != 0 )
      {
         r = temp%10;
         sum = sum + r*r*r;
  temp = temp/10;
      }

      if ( n == sum )

         System.out.println("Entered number is an armstrong number.");
      else
         System.out.println("Entered number is not an armstrong number.");
   }
}

推荐答案

这很简单:根据需要,它将给定数字的多维数据集相加数字,最后,将这个总和与给定的数字本身进行比较。



开始之前,开始, temp 等于 n (给定数字)。

第一次迭代时, r 等于 temp 的最低有效数字(例如,如果数字 123 ,而不是 r = 3 )。然后将 r 的多维数据集添加到 sum 。最后 temp 除以 10 ,丢弃余数(因为它使用整数除法,例如 temp = 123 变为 temp = 12 )。在下一次迭代中重复该过程,直到 temp 变为 0 ,即所有数字都已被使用。 />


您可以使用调试器轻松检查。
It is simple: as required it sums the cubes of the digits of the given number and, at the end, compares such sum with the given number itself.

Before the while starts, temp is equal to n (the given number).
At first iteration, r is equal to the least significant digit of temp (e.g if number is 123, than r=3). Then the cube of r is added to sum. Finally temp is divided by 10, discarding the remainder (because it uses the integer division, e.g. temp=123 becomes temp=12). The process is repeated at next iterations, until temp becomes 0, that is all the digits have been used.

You might easily check it with a debugger.


这是一个很好的建议:停止查看所有类型的垃圾;相反,采用阿姆斯壮的数字定义并自己解决这个非常简单的问题: http://en.wikipedia.org/wiki/ Armstrong_number [ ^ ]。



即使你由于某种原因未能解决它,你也可以在这个论坛上提出一个合理的问题。



-SA
Here is a good advice for you: stop looking at all kind of trash; instead, take the definition of the Armstrong number and solve this really simple problem by yourself: http://en.wikipedia.org/wiki/Armstrong_number[^].

Even if you, by some reason, fail to solve it, you will be able to ask a reasonable question at this forum.

—SA


这篇关于在'while'循环之后我不理解这段代码的逻辑,我知道阿姆斯特朗的概念。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆