使用二分法完成一個簡單的猜商品價格演算法
阿新 • • 發佈:2019-01-08
package cn.kimtian.array.one; import java.util.Scanner; /** * 題目:出示一個任意價格的商品(在XXX-XXX元內),參與者要猜這件商品的價格,然後會有人給出相應高了或低了的提示,直到猜出這個價格為止 * 使用二分法來 * * @author kimtian */ public class AlgorithmOne { public static void main(String[] args) { AlgorithmOne algorithmOne = new AlgorithmOne(); System.out.println("請輸入商品的價格,注意輸入一個整數哦!"); Scanner scanner = new Scanner(System.in); int price = scanner.nextInt(); System.out.println("請輸入要猜的價格範圍,以-分割"); String range = scanner.next(); String nums[] = range.split("-"); //校驗分割後的結果只允許為兩個值,否則格式不通過 if (nums.length != 2) { System.out.println("價格範圍輸入錯誤"); } //比較左右兩個值,哪個大哪個為heightPrice,哪個小哪個為lowPrice else { int num1 = Integer.parseInt(nums[0]); int num2 = Integer.parseInt(nums[1]); if (num1 > num2) { System.out.println(algorithmOne.guessPrice(num2, num1, price)); } else { System.out.println(algorithmOne.guessPrice(num1, num2, price)); } } } /** * 採用二分法 **/ public String guessPrice(int lowPrice, int heightPrice, int price) { // 判斷是否在範圍中,不在就不執行後面了,避免死迴圈 if (price > heightPrice || price < lowPrice) { return "實物價格不在給定範圍中"; } else { int height = heightPrice; int low = lowPrice; int guessPrice = (low + heightPrice) / 2; //記錄一下執行次數 int i = 0; while (guessPrice != price) { // 如果猜大了,那麼最大值就是猜的值 if (guessPrice > price) { height = guessPrice; } // 如果猜小了,那麼最小值就是猜的值 else if (guessPrice < price) { low = guessPrice; } guessPrice = (low + height) / 2; i++; } return "共猜了" + (i + 1) + "次,猜到了價格是:" + guessPrice + "元。"; } } }