寻找兔子算法
今天偶然看到一个小学时经常看到的数学题目,算法很新颖(我自己给他命名为寻找兔子算法),所以就用java实现了一下,实现的很简单纯属自娱,如果你也感觉算法很巧妙请支持一下···
题目描述:已知有鸡和兔15只,共有40只脚,问鸡和兔各有几只?
算法:假设鸡和兔训练有素,吹一声哨,它们抬起一只脚,40-15=25。再吹一声哨,它们又抬起 一只脚,25-15=10,这时鸡都一屁股坐地上了,兔子还两只脚立着。所以,兔子有10÷2=5只,鸡有15-5=10只。注意这种算法不用二元一次方程!!!
package com.abin;
import java.util.Scanner;
public class FindRabbit {
public static void main(String[] args) {
int num_animals = 0;//动物的总数
int num_legs =0;//腿的总数
int num_rabbits = 0;//兔子的总数
Scanner scanner = null;
System.out.println("请输入动物的总数和腿的总数中间使用空格分开:");
scanner = new Scanner(System.in);
if(scanner.hasNextInt())
num_animals = (int) scanner.nextInt();
if(scanner.hasNextInt())
num_legs = (int) scanner.nextInt();
num_rabbits = findRabbit(num_animals,num_legs);
if(num_rabbits!=0)
System.out.println("兔子的个数为:"+num_rabbits);
}
public static int findRabbit(int num_animals, int num_legs){
if (num_animals>=num_legs) {
System.out.println("请检查给定参数···");
}else{
return (num_legs-(2*num_animals))/2;
}
return 0;
}
}
import java.util.Scanner;
public class FindRabbit {
public static void main(String[] args) {
int num_animals = 0;//动物的总数
int num_legs =0;//腿的总数
int num_rabbits = 0;//兔子的总数
Scanner scanner = null;
System.out.println("请输入动物的总数和腿的总数中间使用空格分开:");
scanner = new Scanner(System.in);
if(scanner.hasNextInt())
num_animals = (int) scanner.nextInt();
if(scanner.hasNextInt())
num_legs = (int) scanner.nextInt();
num_rabbits = findRabbit(num_animals,num_legs);
if(num_rabbits!=0)
System.out.println("兔子的个数为:"+num_rabbits);
}
public static int findRabbit(int num_animals, int num_legs){
if (num_animals>=num_legs) {
System.out.println("请检查给定参数···");
}else{
return (num_legs-(2*num_animals))/2;
}
return 0;
}
}