泛型+委托+Lambda表达式+拓展方法的菲波那切数列求解方法

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

namespace Get
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("菲波那切数列:");
            Console.Write("‘+’+ int:");
            Operation.GetStack(1, 2, 20, (x, y) => x + y);
            Console.WriteLine();
            Console.Write("‘-’+ double:");
            Operation.GetStack(1.0d, 2.00d, 20, (x, y) => x - y);
            Console.WriteLine();
            Console.Write("‘*’+ double:");
            Operation.GetStack(1d, 2d, 10, (x, y) => x * y);
            Console.WriteLine();
            Console.Write("‘/’+ double:");
            Operation.GetStack(1d, 2d, 10, (x, y) => x / y);
            Console.WriteLine();
            Console.Write("‘/’+ float:");
            Operation.GetStack(1f, 2f, 10, (x, y) => x / y);
            Console.ReadLine();
        }
    }

    public static class Operation
    {
        //定义一个委托
        public delegate T BiOperator<T>(T x, T y);

        /// <summary>
        /// 求菲波那切数列
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="firstNum">第一个数</param>
        /// <param name="secNum">第二个数</param>
        /// <param name="count">位数</param>
        /// <param name="op">委托</param>
        public static void GetStack<T>(T firstNum, T secNum, int count, BiOperator<T> op)
        {
            Stack st = new Stack();
            st.Push(firstNum);
            T tmp;
            while (st.Count < count)
            {
                tmp = op(st.TPeek<T>(), secNum);//op()的第一个参数返回类型是T,故写了一个Stack的拓展方法
                st.Push(secNum);
                secNum = tmp;
            }
            foreach (var item in st)
            {
                Console.Write(item);
                Console.Write(' ');
            }
        }

        /// <summary>
        /// 返回一个T泛型的栈顶元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="st"></param>
        /// <returns></returns>
        public static T TPeek<T>(this Stack st)
        {
            return (T)st.Peek();
        }
    }
}

 

posted @ 2017-01-03 20:19  花生打代码会头痛  阅读(134)  评论(0)    收藏  举报