Java实现水仙花数
(1)通过输入一个三位数来判断是否为水仙花数(自己做的)
import java.util.Scanner;
/**
*
* 求1000以内的水仙花数
* “水仙花数”—— 指一个三位数其各位数字的立方和等于该数本身
* 例如:153 是水仙花数,因为:
* 153 = 1^3 + 5^3 + 3^3
*/
public class shuixianhua {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//输入一个一千以内的数
System.out.println("请输入一个三位数:");
int num = sc.nextInt();
int individual = 0, ten = 0, hundred = 0, numbers = 0;
//判断输入的数是否小于1000
if (num < 1000){
// 拿到单独每一位数
individual = num % 10; // 个位数
ten = num / 10 % 10; // 十位数
hundred = num / 100; // 百位数
// 测试输出获取到的每一位数
// System.out.println(hundred+", "+ten+", "+individual);
// 获取各位数的立方和
numbers = (int) Math.pow(individual,3) + (int) Math.pow(ten,3) + (int) Math.pow(hundred,3);
// 测试输出
// System.out.println(numbers);
// 判断如果各位数字的立方和是否等于该数本身
if (numbers == num){
System.out.println(num + "为水仙花数!");
}else {
System.out.println(num + "不是水仙花数!!");
}
}
}
}
(2)直接判断1000以内的数中是否有水仙花数(自己做的)
能得出水仙花数,但代码不是最优
import java.util.Scanner;
/**
*
* 求1000以内的水仙花数
* “水仙花数”—— 指一个三位数其各位数字的立方和等于该数本身
* 例如:153 是水仙花数,因为:
* 153 = 1^3 + 5^3 + 3^3
*/
public class shuixianhua {
public static void main(String[] args){
int count = 0; // 水仙花数个数
int counts = 0; // 非水仙花数个数
// 通过for循环100~999的所有数
for(int i=100; i<1000; i++){
int indi = 0, tens = 0, hund = 0, nums = 0;
indi = i % 10; // 拿到单独每一位数 个位数
tens = i / 10 % 10; // 十位数
hund = i / 100; // 百位数
nums = (int) Math.pow(indi,3) + (int) Math.pow(tens,3) + (int) Math.pow(hund,3);
// 判断如果各位数字的立方和是否等于该数本身
if (nums == i){
count += 1;
System.out.println(i + "为水仙花数!");
}else {
//System.out.println(i + "不是水仙花数!!");
counts += counts;
}
}
System.out.println("1000以内共有"+count+"个水仙花数!");
}
}
(2)直接判断1000以内的数中是否有水仙花数(视频教程里的)
import java.util.Scanner;
/**
*
* 求1000以内的水仙花数
* “水仙花数”—— 指一个三位数其各位数字的立方和等于该数本身
* 例如:153 是水仙花数,因为:
* 153 = 1^3 + 5^3 + 3^3
*/
public class shuixianhua {
public static void main(String[] args){
for (int inum=0; inum<1000; inum++){
int a = inum,sums = 0;
while (a > 0){
int b = a % 10;
sums += b * b * b;
a /= 10;
}
if(sums == inum){
System.out.println(inum + "是水仙花");
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/114868.html