- 《孙子算经》
35头,94脚,鸡兔各多少 - 分析:
- 方程:x+y=35,2x+4y=94
public class another {
public static void main(String[]args){
int chicken=0,rabbit=0;
int head,foot;
System.out.printf("输入头数:");
Scanner input=new Scanner(System.in);
head=input.nextInt();
System.out.printf("输入脚数:");
foot=input.nextInt();
System.out.printf("求解结果为:\n");
JTTL(head,foot,chicken,rabbit);
//System.out.printf("鸡有:%d只,兔有:%d只",chicken,rabbit);
}
static void JTTL(int head,int foot,int chicken,int rabbit){
//rabbit=(foot-2*head)/2;
//chicken=head-rabbit;
for(rabbit=0;rabbit<=head;rabbit++){
chicken=head-rabbit;
if((2*chicken+4*rabbit)==foot){
System.out.printf("鸡有:%d只,兔有:%d只",chicken,rabbit);
break;
//return;
}
}
}
}
运行结果
- 另一种思路
- 分析:
- 一只兔子比一只鸡多两只脚,假定全是鸡,剩余的腿数除以二,就是兔子数。即:兔=(脚-2*头)/2; 鸡=头-兔
public class ChickenANDRabbit {
public static void main(String[]args){
int[]chicken={0},rabbit={0};
int head,foot;
System.out.printf("输入头数:");
Scanner input=new Scanner(System.in);
head=input.nextInt();
System.out.printf("输入脚数:");
foot=input.nextInt();
System.out.printf("求解结果为:\n");
JTTL(head,foot,chicken,rabbit);
System.out.printf("鸡有:%d只,兔有:%d只",chicken[0],rabbit[0]);
}
static void JTTL(int head,int foot,int[]chicken,int[]rabbit){
rabbit[0]=(foot-2*head)/2;
chicken[0]=head-rabbit[0];
}
}