鸡兔同笼问题(穷举法)
上有三十五只头,下有九十四只足,问鸡兔各几何
import java.util.Scanner;
public class main {
static int chicken, rabbit;
public static int number(int head, int foot) {
int num, i, j;
num = 0;
for (i = 0; i <= head; i++) {
j = head - i;
if (i * 2 + j * 4 == foot) {
num = 1;
chicken = i;
rabbit = j;
}
}
return num;
}
public static void main(String[] args) {
int num, head, foot;
Scanner sc = new Scanner(System.in);
System.out.println("请输入头的个数:");
head = sc.nextInt();
System.out.println("请输入脚的个数:");
foot = sc.nextInt();
num = number(head, foot);
if (num == 1) {
System.out.println("鸡有" + chicken + "只;兔子有" + rabbit + "只.");
} else {
System.out.println("无法求解!");
}
sc.close();
}
}