- static int chicken,rabbit;
- public static int sun(int m,int n){
- int temp=0;
- int i,j;
- for(i=0;i<=m;i++) {
- j=m-i;
- if(2*i+4*j==n) {
- temp=1;
- chicken=i;
- rabbit=j;
- }
- }
- return temp;
- }
- public static void main(String []args) {
- int temp;
- System.out.println("穷举法求解鸡兔同笼问题");
- Scanner scan =new Scanner (System.in);
- System.out.println("输入头数");
- int head=scan.nextInt();
- Scanner scanner =new Scanner(System.in);
- System.out.println("请输入脚数");
- int foot=scanner.nextInt();
- temp=sun(head,foot);
- if(temp==1) {
- System.out.println("鸡有"+chicken+"只"+""+" 兔有 "+rabbit+" 只 ");
- }
- else {
- System.out.println("输入错误");
- }
- }
来源: http://www.bubuko.com/infodetail-3012321.html