鸡兔同笼java代码

以下是一个Java代码示例,用于解决鸡兔同笼问题:

public class ChickenRabbit {
    public static void main(String[] args) {
        int totalHeads = 35; // 总头数
        int totalLegs = 94; // 总腿数

        int[] result = solveChickenRabbit(totalHeads, totalLegs);
        if (result != null) {
            int chickens = result[0];
            int rabbits = result[1];
            System.out.println("鸡的数量为: " + chickens);
            System.out.println("兔子的数量为: " + rabbits);
        } else {
            System.out.println("无解");
        }
    }

    public static int[] solveChickenRabbit(int totalHeads, int totalLegs) {
        // 鸡有2只脚,兔子有4只脚
        // 根据题意,设鸡的数量为x,兔子的数量为y
        // 则有 x + y = totalHeads
        // 2x + 4y = totalLegs

        // 通过解方程组得到 x 和 y 的值
        double a = 2.0;
        double b = 4.0;
        double c = totalHeads;
        double d = totalLegs;

        double determinant = a * d - b * c;
        if (determinant == 0) {
            return null; // 无解
        }

        double x = (c * d - b * c) / determinant;
        double y = (a * c - b * d) / determinant;

        int chickens = (int) Math.round(x);
        int rabbits = (int) Math.round(y);

        return new int[]{chickens, rabbits};
    }
}

这段代码定义了一个名为ChickenRabbit的类,其中包含一个主方法main和一个求解鸡兔同笼问题的函数solveChickenRabbit。在主方法中,我们设定了总头数和总腿数,然后调用solveChickenRabbit函数来求解鸡和兔子的数量。如果存在解,则输出鸡和兔子的数量;否则,输出"无解"。

你可能感兴趣的:(java,算法,开发语言)