题解 | 小球走过路程计算

小球走过路程计算

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));
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
05-01 13:13
ecece:这么明目张胆虚报就业率啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务