鸡兔同笼问题

鸡兔同笼是古代算数的一个难题,但是在现在的我们看起来似乎很简单。

代码实现:
import java.util.Scanner;

public class test {
    private static int chook;
    private static int hare;
    private static int head = 0;
    private static int foot = 0;
    public static void main(String[] args) {
        show();
    }
    public static void show() {
        //进行数据的录入
        String num = "";
        String[] nums;
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入头和脚的数量(用逗号隔开):");
        try {
            
            while(true) {
                num = sc.nextLine();
                nums = num.split(",|,");
                head = Integer.parseInt(nums[0]);
                foot = Integer.parseInt(nums[1]);
                if(foot%2 != 0) {
                    System.out.println("请输入正确的脚数!!!");
                    continue;
                }else {
                    count();
                    break;
                }
            }
        }catch(Exception e){
            System.out.println("输入有误,退出!!!");
            System.exit(-1);
        }
    
        
    }
    public static void count() {
        //计算鸡兔的数量
        for(int chook = 0;chook <= head;chook++) {
            if((((chook*2)+(head-chook)*4) == foot)){
                hare = head -chook;
                System.out.println("鸡的数量:"+ chook +"兔的数量:"+ hare);
                continue;
            }
        }
    }
}

转载于:https://www.cnblogs.com/lijiafeng/p/7608339.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值