阶乘分之⼀求和公式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;
c语言用递归函数求n的阶乘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()); }
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。