妙趣横生的算法-常胜将军

  现有21根火柴,两人轮流取,每人每次可以取走1至4根,不可多取,也不能不取,谁取最后一根火柴谁输。

  规则,人先取,计算机后取,计算机为“常胜将军”。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 常胜将军
{
    class Program
    {
        static void Main(string[] args)
        {
            //现有21根火柴,两人轮流取,每人每次可以取走1至4根,不可多取,也不能不取,谁取最后一根火柴谁输。规则,人先取,计算机后取,计算机为“常胜将军”
            Console.WriteLine("现有21根火柴,两人轮流取,每人每次可以取走1至4根,不可多取,也不能不取,谁取最后一根火柴谁输。");
            Console.WriteLine("**********************************************************************************************");
            int count = 21;
            while (true)
            {
                Console.WriteLine("剩余{0}火柴",count);
                Console.WriteLine("玩家取火柴");
                int people = Convert.ToInt32(Console.ReadLine());
                if (people == 1 || people == 2 || people == 3 || people == 4)
                {
                    count -= people;//玩家取走火柴
                    if (count==0)
                    {
                        Console.WriteLine("您输了");
                        break;
                    }
                    count -= 5 - people;//电脑取走火柴
                    if (count == 0)
                    {
                        Console.WriteLine("您赢了");
                        break;
                    }
                }
                else
                {
                    Console.WriteLine("您输入的有误!请重新输入...");
                }
            }
            Console.Read();
        }
    }
}

本文出自:妙趣横生的算法

posted @ 2012-10-28 14:41  阿朱姐姐  阅读(273)  评论(0编辑  收藏  举报

友情链接:@开源中国

回到顶部