天天看點

用C#實作的一道公務員考題

某人有15個空啤酒瓶,已知4個啤酒瓶可以換一瓶啤酒,問一共可以換多少瓶瓶酒。
答案是5瓶,因為最後剩餘三個可以找老闆借一個空瓶,等喝完後還給老闆。
前天的C#課上,想到用C#編寫。
實作如下。 
   
  
//
  design by superdont
  //
  lilizong[at]gmail
  
  using
   System;
  class
   Doloop
  ...
  {
    public static void Main()
    ...{
        int[] a =new int[10];
        //用于存放目前的空酒瓶個數
        int[] b = new int[10];
        //用于存放可以換取的酒的瓶數
        int[] c = new int[10];
        //用于存放每次換取後,剩餘的不足4個的酒瓶個數
        a[0] = 15;
        int sum = 0;
        int i;
        for (i = 0; i < 10; i++)
        ...{
            b[i] = a[i] / 4;
            c[i] = a[i] % 4;
            a[i + 1] = c[i] + b[i];
            if (a[i + 1] <= 3)
            ...{
                if (a[i + 1] == 3)
                    b[i+1] = 1;
                    //如果最後剩餘三個,可以找老闆借一個空瓶,多換一瓶啤酒
                break;
            }

        }

        for (i = 0; i < 10; i++)
        ...{
            Console.Write("    {0}", a[i]);
        }
        Console.WriteLine();
        for (i = 0; i < 10; i++)
            Console.Write("    {0}", b[i]);
        Console.WriteLine();
        for (i = 0; i < 10; i++)
            Console.Write("    {0}", c[i]);
        for (i = 0; i < 10; i++)
            sum = sum + b[i];
            //求各次累計的和,即為總計可以換取的瓶數
        Console.WriteLine();
        Console.WriteLine("可以換取的啤酒評述為:");
        Console.WriteLine(sum);


    }




}