鸡兔同笼问题
鸡兔同笼是古代算数的一个难题,但是在现在的我们看起来似乎很简单。
代码实现:
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;
}
}
}
}