2015年12月31日 星期四

C# - 做猜數字遊戲 (1~20)

練習做一個猜數字文字遊戲:
  • 數字範圍 1~20
  • 只能猜 5 次
  • 計算所猜數字總合之平均
##ReadMore##
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace test01
{
    class Program
    {
        static void Main(string[] args)
        {
            int min = 1, max = 20;
            Random r = new Random();
            int ans = r.Next(min, max);
            int count = 0;
            int sum = 0;
            float average = 0.0f;
            int[] guess = new int[5];
            
            Boolean flags = false;

            Console.WriteLine("ans {0}", ans);

            Console.WriteLine("亂數產生 1~20 整數,猜一個數…");
            while (flags == false)
            {
                if (count >= 5)
                {
                    Console.WriteLine("=============================");
                    Console.WriteLine("五次機會用完了!");
                    flags = true;
                }
                else
                {
                    Console.WriteLine("------------ 猜第 {0}/5 次 ---------------", count+1);
                    Console.WriteLine("猜測範圍 {0}~{1}:", min, max);
                    guess[count] = int.Parse(Console.ReadLine());

                    if (guess[count] == ans)
                    {
                        Console.WriteLine("Bingo !");
                        flags = true;
                    }
                    else if (guess[count] < ans)
                    {
                        Console.WriteLine("猜太小,再猜一次");
                        min = guess[count];
                    }
                    else if (guess[count] > ans)
                    {
                        Console.WriteLine("猜太大,再猜一次");
                        max = guess[count];
                    }
                    count++;
                }
            }
            Console.WriteLine("========= 遊戲結束 =========");
            Console.Write("你猜的數目分別是:");
            for (int i = 0; i < count; i++)
            {
                Console.Write("{0} ", guess[i]);
                sum = sum + guess[i];
            }
            average = sum / count;
            Console.Write(",平均:{0}", average);
            Console.Read();
        }
    }
}

沒有留言:

張貼留言