100小球下落面试题

题目:

一球从100米高度自由落下,每次落地后反跳回原高度的一半,再落下,求它在第12次落地时,共经过多少米?第9次反弹多高? (写出实现代码)


public class Test {
	
	/**
	 * 
	 * @param num 次数
	 * @param height 反弹高度
	 * @param sum 经历的距离
	 */
	public static void getHeight(int num, double height, double sum){
		
		System.out.println("num = " + num + ", height = " + height + ", sum = " + sum);
		
		// 第十二次落地的时候退出递归
		if(num == 12){
			return;
		}
		getHeight(++num, height/2, sum + height);
	}
	
	public static void main(String[] args) {
		// 分析:第一次落地:高度100,落地时经历100米
		//	 第二次落地:高度50,落地时经历 100 + 50 + 50
		//	 第三次落地:高度25,落地时经历 200 + 25 + 25
		
		// 初始 num = 1,height = 100,sum = 100
		getHeight(1, 100, 100);
	}

}
num = 1, height = 100.0, sum = 100.0
num = 2, height = 50.0, sum = 200.0
num = 3, height = 25.0, sum = 250.0
num = 4, height = 12.5, sum = 275.0
num = 5, height = 6.25, sum = 287.5
num = 6, height = 3.125, sum = 293.75
num = 7, height = 1.5625, sum = 296.875
num = 8, height = 0.78125, sum = 298.4375
num = 9, height = 0.390625, sum = 299.21875
num = 10, height = 0.1953125, sum = 299.609375
num = 11, height = 0.09765625, sum = 299.8046875
num = 12, height = 0.048828125, sum = 299.90234375


第十二次落地经历: 299.90234375

第九次反弹高度: 0.1953125

你可能感兴趣的:(模拟)