题解 | #求小球落地5次后所经历的路程和第5次反弹的高度#
求小球落地5次后所经历的路程和第5次反弹的高度
https://www.nowcoder.com/practice/2f6f9339d151410583459847ecc98446
package com.chen.test.huawei;
import java.util.Scanner;
/**
* 假设一个球从任意高度自由落下,每次落地后反跳回原高度的一半; 再落下, 求它在第5次落地时,共经历多少米?第5次反弹多高?
* 数据范围:输入的小球初始高度满足 1≤n≤1000 ,且保证是一个整数
*
* 对于n米的球:
* 总的长度: n*(1+ 1/2 + 1/2 + 1/4 + 1/4 + 1/8 + 1/8 + 1/16 + 1/16)
* 第5次反弹height: n/16
*/
public class HJ38StatisticBallLengthAndHeight {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()){
//要求输入一个整数
findLengthAndHeight(sc.nextInt());
}
sc.close();
}
private static void findLengthAndHeight(double num){
double length = 0.0;
double height= 0.0;
for (int i = 0; i < 5; i++) {
if(i==0){
length = num;
height = num/2;
}else {
//因为每次落地后弹起,再落地长度是一样的
length += height*2;
height = height/2;
}
}
System.out.println(length);
System.out.println(height);
}
}
查看3道真题和解析