您的位置 首页 java

Java水仙花数

 public class Demo_3 {
	public static void main(String[] args){
		/* /  %
		 * 案例:判断一个数字是否为水仙花数
		 *     水仙花数:3位数、每一为数字的三次方的和等于它本身,那么这个数字就是水仙花数
		 *     eg:153
		 *         百:1   153/100=1
		 *         十:5   153%100/10=5 [53/10=5]
		 *         个:3   153%100%10=3 [53%10=3]
		 *         1^3 + 5^3 + 3^3 == 153【水仙花数】
		 *    问题关键:怎们去获取这个三位数字的每一个位置上的数字
		 * 案例:输出100-1000以内的水仙花数
		 *     for循环
		 *     语法:
		 *     for(起始值;终止值;迭代){代码操作}
		 *     起始值:100
		 *     终止值:1000
		 *     迭代:每一次循环之后让起始值+1
		 *          i++ 表示自增运算符【每一次循环结束之后让自身+1】
		 *     for(int i=100;i<1000;i++){}
		 * */
		int num = 153;
		int b = num/100;//百位
		int s = num%100/10;//十位
		int g = num%100%10;//个位
		System.out.println("百位:" + b + ",十位:" + s + ",个位:" + g);
		/*
		 * Math java类
		 * pow(double a, double b) 方法
		 * double a,double b 是参数
		 * a:表示要求哪一个数字的b次方
		 * b:表示求a这个数字的几次方
		 * Math.pow(2,3) 2的3次方 调用方法 等同于:2*2*2
		 * */
		if((Math.pow(b, 3)+Math.pow(s, 3)+Math.pow(g,3)) == num){
			System.out.println( num + "是水仙花数");
		}else {
			System.out.println("不是水仙花数");
		}
		// 输出100-1000以内的水仙花数
		int b_1;// 声明一个变量
		int s_1;
		int g_1;
		System.out.println("100-1000以内的水仙花数为:");
		for(int i = 100;i<1000;i++){
			b_1 = i/100;
			s_1 = i%100/10;
			g_1 = i%100%10;
			if((Math.pow(b_1, 3)+Math.pow(s_1, 3)+Math.pow(g_1,3)) == i){
				System.out.print(i + "t");
			}
		}
	}
}
  

文章来源:智云一二三科技

文章标题:Java水仙花数

文章地址:https://www.zhihuclub.com/172250.shtml

关于作者: 智云科技

热门文章

网站地图