close
  • 籠子裡有雞兔,只知道共有26隻腳,8個頭,求雞兔各有幾隻?
import java.util.Scanner;public class P4_7 {	public static void main(String[] args) {
		Scanner scn = new Scanner(System.in);		System.out.println("請輸入共有幾隻腳?");		int foot = scn.nextInt();		System.out.println("輕輸入共有幾個頭?");		int head = scn.nextInt();
		// 利用for迴圈將可能的雞兔組合都測試過一次		// 答案只有一個,只有符合總腳隻數量之雞兔組合才正確		for (int i = 1; i < head; i++) {		if (((i * 4) + ((head - i) * 2)) == foot) {		System.out.printf("兔子有 %d 隻,小雞有 %d 隻", i, (head - i));			}		}		scn.close();	}}
  • 輸出結果(這裡需要輸入是程式可作為解題用):
請輸入共有幾隻腳?26輕輸入共有幾個頭?8兔子有 5 隻,小雞有 3 隻
arrow
arrow

    ALVIN 發表在 痞客邦 留言(0) 人氣()