`

n的阶乘分之一之和

阅读更多
//求n的阶乘分之一的和

int n;
            Console.WriteLine("请输入n!");
            try
            {
                n = Convert.ToInt32(Console.ReadLine());
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            float sum = 1;
            decimal total = 0;
            for (int i = 1; i <= n; i++)
            {
                sum *= i;
                total += 1m/ sum;
                Console.WriteLine("递归数"+i+"是"+sum);
            }
            Console.WriteLine("被一除的和是"+total);


//用递归实现
   
class F1
{
    public decimal F(int n)
    {
        decimal d;
        if (n < 0)
            return -1;
        if (n == 0 || n == 1)
        {
            return 1;
        }
        else
        {
            d = 1m / n * F(n - 1);
        }
        return d;
    }
}
class Test
{
    static void Main()
    {           
        int b;
        F1 f = new F1();
        do
        { 
            try
            {
                b = Convert.ToInt32(Console.ReadLine());
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            if (b < 0)
            {
                Console.WriteLine("你输入的数必须大于等于0!");
            }
            if (b == 0)
            {
                Console.WriteLine("1");
            }
            else
            {
                decimal a = 0;  
                while (b > 0)
                {
                    a += f.F(b);
                    b--;
                }
                Console.WriteLine(a);
            }
        } while ("Q" != Console.ReadLine());
    }
}
       


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics