基本演算法思想-窮舉演算法
阿新 • • 發佈:2019-01-14
package com.xj.www.algo; import java.util.Scanner; /** * 窮舉演算法 * @author xiongjing * */ public class AlgorithmTest { // chichen雞的個數,rabbit兔的個數 static int chichen, rabbit; // 演算法具體實現 public static int qiongJu(int head, int foot) { int re, i, j; re = 0; for (i = 0; i <= head; i++) { j = head - i; // 雞的腳+兔的腳=總數量 if (i * 2 + j * 4 == foot) { re = 1; chichen = i; rabbit = j; } } return re; } // 程式主入口 public static void main(String[] args) { int re, head, foot; System.out.println("窮舉演算法求解雞兔同籠問題:"); System.out.println("請輸入頭數:"); @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); head = sc.nextInt(); System.out.println("請輸入腳數:"); foot = sc.nextInt(); re = qiongJu(head, foot); if (re == 1) { System.out.println("雞有" + chichen + "只,兔有" + rabbit + "只"); } else { System.out.println("無法求解"); } } }