经典面试题 苦逼的我在面试中做错了 回来以后硬是敲了56次
血的教训啊 不多说直接上代码
package interview_code;
/**
* 一个球从100m高度自由落下,每次落地后反弹回原来高度的一半,再落下。求它在第10次落地并反弹到最高点,共经过多少m?第10次反弹多高?
* @className: Higth
* @description:
* @author: singleton-zw
* @createDate: 2016年3月4日-下午2:55:17
* @updateAuthor:
* @updateDate:
* @updateDesc:
* @version: v1.0
* @Copyright (c)-2016
*/
public class Higth {
public static void main(String[] arg) {
geth();
System.out.println();
getHigth();
}
/**
* 网络版
* 一个球从100m高度自由落下,每次落地后反弹回原来高度的一半,再落下。求它在第10次落地并反弹到最高点,共经过多少m?第10次反弹多高?
* @methodsDescription:
* @methodName: getHigth
* @author: singleton-zw
* @return: void
*/
public static void getHigth(){
float l = 100f;
float s = l; //第一次落地
for (int i = 0; i < 9; i++) {
l /= 2;
if (i == 10) {//最后一次只弹起不落地
s += l;
} else {
s += 2 * l;
}
}
System.out.println("经过" + s + "米,最后一次高" + l + "米");
}
/**
* 复杂版
* 一个球从100m高度自由落下,每次落地后反弹回原来高度的一半,再落下。求它在第10次落地并反弹到最高点,共经过多少m?第10次反弹多高?
* @methodsDescription:代码量复杂
* @methodName: geth
* @author: singleton-zw
* @return: void
*/
public static void geth(){
float h = 100f;
float s = h;
float higth = 0f;
//第一次只有下没有上
for(int i =1;i<10;i++){
//反弹后的高度
higth = getReturnHigth(h);
System.out.println("第"+(i+1)+"弹起的距离--"+higth);
//再去求反弹的路径
h = higth;
//要注意的是第二次的距离是下去加反弹的距离 (注意的是原来一半的距离)
s += (higth*2);
System.out.println("第"+(i+1)+"整次过程----"+s);
}
System.out.println("所有:"+s +" 最后一次"+higth);
}
/**
*
* @methodsDescription:算出反弹数
* @methodName: getReturnHigth
* @param s
* @return
* @author: singleton-zw
* @return: float
*/
public static float getReturnHigth(float s){
return s/2;
}
}
有些bt的公司要结果 那我就给你们
第2弹起的距离--50.0
第2整次过程----200.0
第3弹起的距离--25.0
第3整次过程----250.0
第4弹起的距离--12.5
第4整次过程----275.0
第5弹起的距离--6.25
第5整次过程----287.5
第6弹起的距离--3.125
第6整次过程----293.75
第7弹起的距离--1.5625
第7整次过程----296.875
第8弹起的距离--0.78125
第8整次过程----298.4375
第9弹起的距离--0.390625
第9整次过程----299.21875
第10弹起的距离--0.1953125
第10整次过程----299.60938
所有:299.60938 最后一次0.1953125
经过299.60938米,最后一次高0.1953125米