Java语言用什么语句可以简洁解决乌龟爬行问题,乌龟奇数天每天向前爬行3米,偶数天每天向后爬行距起点一半,n从键盘输入

Java语言用什么语句可以简洁解决乌龟爬行问题,乌龟奇数天每天向前爬行3米,偶数天每天向后爬行距起点一半,多少天可以爬行n米,n从键盘输入,怎么实现呢

效果如图

img

代码如下

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("请输入要爬行的距离(米):");
        int distance = scanner.nextInt();

        int days = 0; // 爬行的天数
        int currentDistance = 0; // 当前已经爬行的距离
        int step = 3; // 默认每次爬行的固定步长

        while (currentDistance < distance) {
            days++;
            if (days % 2 == 0) { // 偶数天向后爬行距起点一半
                step = currentDistance / 2;
            } else { // 奇数天向前爬行3米
                step = 3;
            }

            currentDistance += step;
        }

        System.out.println("乌龟爬行了 " + days + " 天,爬行距离为 " + currentDistance + " 米。");
    }
}