算法——二分法试猜商品价格

看商品猜价格

首先出示一件价格在999元以内的商品,参与者要猜出这件商品的价格。在猜价格的过程中,主持人会根据参与者给出的价格,相应地给出“高了”或“低了”的提示。商品实际价格640。

 

表1-1 二分法猜商品价格

次数

价格区间

中间值

第1次

0-999

500

第2次

500-999

750

第3次

500-750

620

第4次

620-750

680

第5次

620-680

650

第6次

620-650

630

第7次

630-650

640

 

C#代码实现            int lowerBound;    //商品价格范围值的下界
            int upperBound;    //商品价格范围值的上界
            int realPrice;     //商品的实际价格
            int guessPrice;    //试猜价格

            #region 设置参数

            Console.WriteLine("1.设置参数------");
            Console.Write("请设置商品价格范围值的下界: ");
            string strLowBond = Console.ReadLine();
            lowerBound = Convert.ToInt32(strLowBond);

            Console.Write("请设置商品价格范围值的上界: ");
            string strUpBound = Console.ReadLine();
            upperBound = Convert.ToInt32(strUpBound);

            Console.Write("请设置商品的实际价格: ");
            string strRealPrice = Console.ReadLine();
            realPrice = Convert.ToInt32(strRealPrice);
            Console.WriteLine("设置成功,按任意键清屏!");
            Console.ReadLine();
            Console.Clear();

            #endregion

            #region 二分法自动猜商品价格
            Console.WriteLine("2.猜商品价格------");
            int count = 1;    //试猜次数
            guessPrice = 0;

            while (guessPrice!=realPrice)
            {
                guessPrice = (lowerBound + upperBound) / 2;
                Console.WriteLine("" + count + "次: " + guessPrice);
                if (guessPrice > realPrice)
                {
                    upperBound = guessPrice;

                    Console.WriteLine("高了");
                }
                else if (guessPrice < realPrice)
                {
                    lowerBound = guessPrice;

                    Console.WriteLine("低了");
                }
                else
                {
                    Console.WriteLine("恭喜猜对了");
                }

                count=count+1;
            }

            #endregion

 

Matlab代码实现%二分法猜商品价格
clear,close all

format short;
disp('1.设置参数------');
lowerBound=input('请设置商品价格范围值的下界: ');
upperBound=input('请设置商品价格范围值的上界: ');
realPrice=input('请设置商品的实际价格: ');

count=1;
guessPrice=0;

disp('2.猜商品价格------');
while guessPrice~=realPrice,
	guessPrice = floor((lowerBound + upperBound) / 2);
	fprintf('第 %d 次: %d',count,guessPrice);
    
	if guessPrice>realPrice
    	upperBound = guessPrice;
        fprintf('\n');
        disp('高了');
    elseif guessPriceelse 
        fprintf('\n');
       	disp('恭喜猜对了!');
    end  
        count=count+1;
end

 

运行结果

算法——二分法试猜商品价格_第1张图片

算法——二分法试猜商品价格_第2张图片

由上可见,只需要6次即可猜出商品价格,由于给出的实例表格中并未严格按照二分法进行试猜,结果比运行实例多出1次。对比表明严格按照二分法试猜要优于近似按照二分法试猜。

转载于:https://www.cnblogs.com/6DAN_HUST/archive/2011/07/24/2115600.html

你可能感兴趣的:(matlab,c#)