2017-07-28 168 views
-5
INT分配

我想在阿姆斯特朗数工作, 因此,这里是我的代码混淆在Java

public class NewArmStrongNumber { 

public static void main(String[] args) { 

    int num = 153,armNum=0; 
    while(num>0){ 
     int temp = num%10; 
     armNum = armNum+(temp*temp*temp); 

     num = num/10; 

    } 
    System.out.println(num==armNum); 

} 

}

我得到的结果是假的,我可以知道为什么吗?

+3

您将能够告诉更快,如果你跑了在调试器中编写代码,设置一个断点,然后逐步了解您的假设是否不正确。 – duffymo

+0

最后,num = 0.尝试在循环之前使用'temp2 = num'将'num'的值存储到某个'temp2'变量中,最后做'System.out.println(temp2 == armNum); ' –

回答

0

NUM正在减小,因为它是/ 10各一次,并且当num是0

环路退出armNum每次使其通过循环时间可能增加。

因此,除非armNum为0,否则将是错误的。

0

您必须将num保存在其他变量中才能将其与armNum进行比较。这是因为numwhile循环的末尾将始终为。所以(num==armNum)永远是false

0

防雷工程,根据Armstrong numbers定义:

package math.numbers; 

import java.util.List; 
import java.util.stream.Collectors; 
import java.util.stream.IntStream; 

/** 
* Created by Michael 
* Creation date 7/28/2017. 
* @link https://stackoverflow.com/questions/45378317/confused-with-int-assignments-in-java 
* @link http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/arms.html 
*/ 
public class Armstrong { 

    public static void main(String[] args) { 
     List<Integer> armstrong = IntStream.range(0, 1000000).filter(Armstrong::isArmstrong).boxed().collect(Collectors.toList()); 
     System.out.println(armstrong); 
    } 

    public static boolean isArmstrong(int n) { 
     boolean armstrong = false; 
     int sum = 0; 
     int temp = n; 
     while (temp > 0) { 
      int x = temp % 10; 
      sum += x * x * x; 
      temp /= 10; 
     } 
     armstrong = (sum == n); 
     return armstrong; 
    } 
} 

这里的输出我得到:

[0, 1, 153, 370, 371, 407]