网上有关“用Java写个关于“水仙花数”的程序?”话题很是火热,小编也是针对用Java写个关于“水仙花数”的程序?寻找了一些与之相关的一些信息进行分析,如果能碰巧解决你现在面临的问题,希望能够帮助到您。
public static void main(String[] args) {
//第一种方法
//第二种方法
int a,b,c,m;
for(int i=1;i<=9;i++){//a为百位数字,不能为0
a=i;
for(int j=0;j<=9;j++){
b=j;
for(int k=0;k<10;k++){
c=k;
m=a*100+b*10+c;
if (m==a*a*a+b*b*b+c*c*c) {
System.out.println("\t"+m);
}
}
}
}
}
水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。
(例如:1^3 + 5^3+ 3^3 = 153)
创建工程,或使用已有工程,在工程下创建包,包内新建一个类,命名为Narcissistic类,根据自己喜好随便命名,但请保持类名与文件名一致。
先写一个函数计算一个数字的立方为多少。命名为cube()
private static int cube(int n) {
return n * n * n;
}
判断这个数是不是水仙花数,求每一位数上的数的立方和是否为原数字本身。
private static Boolean isNarcissistic(int number) {
int hundreds = number / 100;
int tens = number / 10 - hundreds * 10;
int ones = number % 10;
return cube(hundreds) + cube(tens) + cube(ones) == number;
}
写一个for循环来判断那些数字是水仙花数,并输出。
for (int index = 100; index < 1000; ++index) {
if (isNarcissistic(index))
System.out.print(index + "\t");
}
关于“用Java写个关于“水仙花数”的程序?”这个话题的介绍,今天小编就给大家分享完了,如果对你有所帮助请保持对本站的关注!