为什么while()创造了魔法?

时间:2015-12-19 17:05:40

标签: java while-loop

我正在编写一个程序来查找从100到999的非常强的数字。如果我输入数字作为输入程序有效但如果我使用while循环检查数字它会说每个数字都不是一个非常强的数字。我不明白为什么。

这就是代码:

 package armstrong;

 //import java.util.Scanner;

 public class Armstrong {


    public static void main(String[] args) {
        int n, sum = 0, temp, remainder, digits = 0;

        //Scanner in = new Scanner(System.in);
        //System.out.println("Input a number to check if it is an Armstrong number");      
        //n = in.nextInt();
        n = 100;
        while (n <= 999) {
            temp = n;

            // Count number of digits

            while (temp != 0) {
                digits++;
                temp = temp / 10;
            }

            temp = n;

            while (temp != 0) {
                remainder = temp % 10;
                sum = sum + power(remainder, digits);
                temp = temp / 10;
            }

            if (n != sum) System.out.println(n + " is not an Armstrong number.");
            else System.out.println("Armstrong number:" + n);

            n++;

        }
    }

    static int power(int n, int r) {
        int c, p = 1;

        for (c = 1; c <= r; c++)
        p = p * n;

        return p;
    }
 }

2 个答案:

答案 0 :(得分:1)

你应该在你的循环中初始化数字,总和为零:

{{1}}

答案 1 :(得分:0)

基于此页面:http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/arms.html

您应该在循环内将sum设置为零:

    while(n <= 999) {
  temp = n;
  sum = 0;
  ...
}

power方法应为:

static int power(int n) {
  return n * n * n;
 }

希望它有所帮助。