求水仙花数,并统计水仙花数。
标题所谓水仙花数,是指一个三位数abc,如果满足a3+b3+c3=abc,则abc 是水仙花数。
for循环:
public class ForDemo {
public static void main(String[] args) {
//定义一个统计量count
int count = 0;
for(int x = 100;x<1000;x++) {
int a = x%10;
int b =x/10%10;
int c =x/10/10%10;
if (x == (a*a*a+b*b*b+c*c*c)) {
System.out.println("水仙花数是:"+x);
count ++ ;
}
}
System.out.println("水仙花数共有:"+count);
}
}
while循环:
public class WhileDemo {
public static void main(String[] args) {
//定义一个统计量
int count = 0;
//定一个一个初始化语句
int x = 100;
while(x<1000) {
x++;
int a = x%10;
int b =x/10%10;
int c =x/10/10%10;
if (x == (a*a*a+b*b*b+c*c*c)) {
System.out.println("水仙花数是:"+x);
count ++ ;
}
}
System.out.println("水仙花数共有:"+count);
}
}
运行结果: