1. 程式人生 > >【Java演算法學習】雞兔同籠問題

【Java演算法學習】雞兔同籠問題

不說廢話,貼程式碼
/**
 * 雞兔同籠問題:窮舉演算法思想
 */
import java.util.*;
public class ChichenAndHabbit {
	static int chichenNum,habbitNum;
	public static void main(String[] args) {
		int head,foot;
		boolean flag;
		System.out.println("窮舉演算法求解雞兔同籠問題");
		System.out.println("請輸入頭數:");
		Scanner input = new Scanner(System.in);
		head = input.nextInt();
		
		System.out.println("請輸入腳的數目?");
		foot = input.nextInt();
		flag = exhaustAgm(head,foot);
		if (flag == true ) {
			System.out.print("雞有"+chichenNum+"只,兔有"+habbitNum+"只。");
		}else {
			System.out.print("無法求解");
		}
	}
		
	public static boolean exhaustAgm(int head, int foot){
		boolean flag = false;
		for (int i = 0; i <= head; i++) {
			int j = head - i;
			if (i*2+j*4 == foot) {//判段,如果找到答案
				flag = true;
				chichenNum = i;
				habbitNum = j;
			}
		}
		return flag;		
	}
	
}