大家好,又见面了,我是你们的朋友全栈君。
ShuiXianHua.java
public class ShuiXianHua{
public static void main(String[] args){
for(int i=100;i<1000;i++){
int x =i/100;
int y =i/10%10;
int z =i%10;
if (x*x*x + y*y*y + z*z*z == i){
System.out.println(x+","+y+","+z+"|"+"三位水仙花数是:"+i);
}
}System.out.println("======再来看看其他的呗======");
for(int j=1000;j<10000;j++){
int a =j/1000;
int b =j/100%10;
int c =j/10%10;
int d =j%10;
if(a*a*a*a + b*b*b*b + c*c*c*c +d*d*d*d == j) {
System.out.println(a+","+b+","+c+","+d+"|"+"四位水仙花是:"+j);
}
}System.out.println("======还有还有,别走,再看看呗======");
for(int o=10000;o<100000;o++){
int q=o/10000;
int w=o/1000%10;
int e=o/100%10;
int r=o/10%10;
int t=o%10;
if(q*q*q*q*q + w*w*w*w*w + e*e*e*e*e + r*r*r*r*r + t*t*t*t*t ==o){
System.out.println(q+","+w+","+e+","+r+","+t+"|"+"五位水仙花是:"+o);
}
}
}
}
输出结果:
1,5,3|三位水仙花数是:153
3,7,0|三位水仙花数是:370
3,7,1|三位水仙花数是:371
4,0,7|三位水仙花数是:407
======再来看看其他的呗======
1,6,3,4|四位水仙花是:1634
8,2,0,8|四位水仙花是:8208
9,4,7,4|四位水仙花是:9474
======还有还有,别走,再看看呗======
5,4,7,4,8|五位水仙花是:54748
9,2,7,2,7|五位水仙花是:92727
9,3,0,8,4|五位水仙花是:93084
在学习的过程中,老师告诉我们,使用Math.pow(a,b):可以更简便代替 (x * x * x ) 在Math.pow的括号内,可以是两个double类型,计算出来的结果也是double类型。
所以,代码可以优化为:
public class ShuiXianHua{
public static void main(String[] args){
for(int i=100;i<1000;i++){
if (Math.pow(i/100,3) + Math.pow(i/10%10,3) + Math.pow(i%10,3) == i){
System.out.println(x+","+y+","+z+"|"+"三位水仙花数是:"+i);
}
}
}
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/157131.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有