Skip to content

Latest commit

 

History

History
63 lines (43 loc) · 1.91 KB

File metadata and controls

63 lines (43 loc) · 1.91 KB

Java 程序:使用函数显示间隔之间的阿姆斯特朗数

原文: https://www.programiz.com/java-programming/examples/armstrong-number-function

在此程序中,您将学习如何使用 Java 中的函数显示两个给定间隔(低和高)之间的所有阿姆斯特朗数。

为了找到两个整数之间的所有阿姆斯特朗数,创建了checkArmstrong()函数。 此函数检查号码是否为阿姆斯特朗

示例:两个整数之间的阿姆斯特朗数

public class Armstrong {

    public static void main(String[] args) {

        int low = 999, high = 99999;

        for(int number = low + 1; number < high; ++number) {

            if (checkArmstrong(number))
                System.out.print(number + " ");
        }
    }

    public static boolean checkArmstrong(int num) {
        int digits = 0;
        int result = 0;
        int originalNumber = num;

        // number of digits calculation
        while (originalNumber != 0) {
            originalNumber /= 10;
            ++digits;
        }

        originalNumber = num;

        // result contains sum of nth power of its digits
        while (originalNumber != 0) {
            int remainder = originalNumber % 10;
            result += Math.pow(remainder, digits);
            originalNumber /= 10;
        }

        if (result == num)
            return true;

        return false;
    }
}

运行该程序时,输出为:

1634 8208 9474 54748 92727 93084 

在上面的程序中,我们创建了一个名为checkArmstrong()的函数,该函数采用参数num并返回布尔值。

如果数字是阿姆斯特朗数,则返回true。 如果不是,则返回false

根据返回值,在main()函数内的屏幕上打印数字。