题目:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在 第10次落地时,共经过多少米?第10次反弹多高?
这个题目,下面我会贴出来两种代码。其实这个题目,我烦了简单计算,想搞得有趣味性一点,结果耽误了好几天时间,最后发现搞的也不好。
先第一种,为了解题而解题。
==== Main.java ====
public class Main {
private double TotalHeight = 100;
private double CurHeight = 50;
public void drop(int times) {
if ((times - 1) == 0) {
return;
}
setTotalHeight(getTotalHeight() + 2 * getCurHeight());
setCurHeight(getCurHeight() / 2);
drop(times - 1);
}
public double getTotalHeight() {
return TotalHeight;
}
public void setTotalHeight(double totalHeight) {
TotalHeight = totalHeight;
}
public double getCurHeight() {
return CurHeight;
}
public void setCurHeight(double curHeight) {
CurHeight = curHeight;
}
public static void main(String[] args) {
Main main = new Main();
main.drop(2);
System.out.println("Total height is " + main.getTotalHeight());
System.out.println("Current height is " + main.getCurHeight());
}
} |