在这里,我们将编写一个 java 程序,检查给定的数字是否为 Armstrong 数。我们将看到同一程序的两个变体。在第一个程序中,我们将在程序本身中分配数字,在第二个程序中,用户将输入数字,程序将检查输入数字是否为 Armstrong。
在我们完成该计划之前,让我们看看什么是阿姆斯特朗数字。如果以下等式适用于该数字,则一个数字称为 Armstrong 数:
xy..z = xn + yn+.....+ zn
其中n表示数字中的位数
例如,这是一个 3 位数的阿姆斯特朗数字
370 = 33 + 73 + o3 = 27 + 343 + 0 = 370
示例 1:用于检查给定数字是否为 Armstrong 数的程序
public class JavaExample { public static void main(String[] args) { int num = 370, number, temp, total = 0; number = num; while (number != 0) { temp = number % 10; total = total + temp*temp*temp; number /= 10; } if(total == num) System.out.println(num + " is an Armstrong number"); else System.out.println(num + " is not an Armstrong number"); }}输出:
370 is an Armstrong number
在上面的程序中我们使用了while循环,但是你也可以使用for循环。要使用for循环,请使用以下代码替换程序的while循环部分:
for( ;number!=0;number /= 10){ temp = number % 10; total = total + temp*temp*temp;}示例 2:用于检查输入数字是否为 Armstrong 的程序
import java.util.Scanner;public class JavaExample { public static void main(String[] args) { int num, number, temp, total = 0; System.out.println("Ënter 3 Digit Number"); Scanner scanner = new Scanner(System.in); num = scanner.nextInt(); scanner.close(); number = num; for( ;number!=0;number /= 10) { temp = number % 10; total = total + temp*temp*temp; } if(total == num) System.out.println(num + " is an Armstrong number"); else System.out.println(num + " is not an Armstrong number"); }}
输出:
Ënter 3 Digit Number371371 is an Armstrong number
