计算小球轨迹:
题目:有一个小球,从100米的高度落地,每次弹起来是原来下落高度的一半,求落地十次小球走的轨迹距离。
采用递归的思想,除了第一次小球落地需要不同外,剩下的的九次小球落地的距离为,n-1次小球的距离+2*小球弹起的高度。
java 递归算法如下:
public class Snippet {
public static void main(String[] args) {
Snippet snippet = new Snippet();
float total = snippet.totalheight(10, 100);
System.out.print(total);
}
public float totalheight(int n, float lenth) {
if (n == 1) { //递归边界 当小球第一次落下 返回100 米
return 100;
}
if (n > 0) {
System.out.println(lenth);//n-1 次走的距离
return lenth + 2 * (totalheight(n - 1, lenth / 2) / 2);//n-1:每次下落n-1;因为走的是来回所以乘2,每次距离都为原来的一半。这样书写便于理解
}
return 0;
}
}
结果:
100.0
50.0
25.0
12.5
6.25
3.125
1.5625
0.78125
0.390625
10 次一共走了:299.60938