AJ031 Java小练习03答案

1、 打印出100~1000范围内的所有 “水仙花数”。所谓“水仙花数”是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个“水仙花数”,153= 1^3 + 5^3 + 3^3。

public class Test03 {
	public static void main(String[] args) {
		int i, j, k;
		for (int x = 100; x < 1000; x++) {
			i = x / 100;				// 百位数
			j = (x / 10) % 10;			// 十位数
			k = x % 10;					// 个位数
			if (x == i * i * i + j * j * j + k * k * k) {
				System.out.print(x + "、");
			}
		}
	}
}

2、将两个整数的内容进行互换。

方法一:使用中间变量

public class Test04 {
	public static void main(String[] args) {
		int x = 10;
		int y = 20;
		int temp = x;
		x = y;
		y = temp;
		System.out.println("x = " + x);
		System.out.println("y = " + y);
	}
}	

方法二:利用数学计算完成

public class Test05 {
	public static void main(String[] args) {
		int x = 10;
		int y = 20;
		x += y ;
		y = x - y;
		x = x - y ;
		System.out.println("x = " + x);
		System.out.println("y = " + y);
	}
}

3、 判断某个数能否被3,5,7同时整除。

public class Test06 {
	public static void main(String[] args) {
		int data = 105;
		if (data % 3 == 0 && data % 5 == 0 && data % 7 == 0) {
			System.out.println(data + "可以同时被3、5、7整除。");
		} else {
			System.out.println(data + "不可以同时被3、5、7整除。");
		}
	}
}

4、 用while循环、do…while循环和for循环求出100~200累加的和。

4.1 使用while循环

public class Test07 {
	public static void main(String[] args) {
		int sum = 0;
		int x = 100;
		while (x <= 200) {
			sum += x;
			x++;
		}
		System.out.println("累加结果:" + sum);
	}
}

4.2 使用do…while循环

public class Test08 {
	public static void main(String[] args) {
		int sum = 0;
		int x = 100;
		do {
			sum += x;
			x++;
		} while (x <= 200);
		System.out.println("累加结果:" + sum);
	}
}

4.3 使用for循环

public class Test09 {
	public static void main(String[] args) {
		int sum = 0;
		for (int x = 100; x <= 200; x++) {
			sum += x;
		}
		System.out.println("累加结果:" + sum);
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章