阶乘分之一求和公式C语言,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());
}
}
總結
以上是生活随笔為你收集整理的阶乘分之一求和公式C语言,n的阶乘分之一之和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在VMware中安装ArchLinux
- 下一篇: 教你如何发布自己的网站