Java算法--穷尽算法 鸡兔同笼问题

时间:2020-11-29 11:24:05

代码:

 

package com.xu.main;

import java.util.Scanner;

public class P6_1 {

static int chicher,habbit;
public static int qiongJu(int head,int foot)
{
int re,i,j;
re = 0;
for(i=0;i<=head;i++)
{
j = head - i;
if(i*2 + j*4 == foot)
{
re = 1;
chicher = i;
habbit = j;

}
}
return re;
}
public static void main(String[] args) {
int re,head,foot;
System.out.println("穷尽算法求解鸡兔同笼问题:");
System.out.println("请输入头数:");
Scanner input = new Scanner(System.in);
head = input.nextInt();
System.out.println("请输入脚数:");
foot = input.nextInt();
re = qiongJu(head, foot);
if(re == 1)
{
System.out.println("鸡有"+chicher+"只,兔有"+habbit+"只");
}
else
{
System.out.println("无法求解!");
}
}

}


 

运行结果:

Java算法--穷尽算法 鸡兔同笼问题