题解 | 小球走过路程计算
小球走过路程计算
https://www.nowcoder.com/practice/ddbb7021c0a7452f9044564234616913
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
float h = scanner.nextFloat();
int n = scanner.nextInt();
double sum = 0; // 总经过的距离
double reboundHeight = h; // 第n次反弹的高度
// 计算总经过的距离和第n次反弹的高度
for (int i = 0; i < n; i++) {
sum += h; // 每次下落的距离
h /= 2; // 反弹高度是原来的一半
if (i < n - 1) { // 除了最后一次反弹,每次反弹都要加上反弹的距离
sum += h;
}
reboundHeight /= 2; // 更新第n次反弹的高度
}
// 输出第n次反弹的高度和总经过的距离
System.out.println(String.format("%.3f", reboundHeight) + " " + String.format("%.3f", sum));
}
}
查看3道真题和解析
