用C#求Sn=1!+2!+3!+4!+5!+…+n!之值,其中n是一个数字(n不超过20)。
时间: 2023-10-10 14:05:08 浏览: 64
对于给定的n,我们可以使用循环来计算Sn的值。以下是使用C#代码实现的示例:
```csharp
using System;
class Program
{
static void Main(string[] args)
{
Console.Write("请输入一个数字n(n不超过20):");
int n = int.Parse(Console.ReadLine());
long sum = 0;
long factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
sum += factorial;
}
Console.WriteLine("Sn的值为:" + sum);
Console.WriteLine("相关问题:");
相关问题
c#1!+2!+3!+4!+5!
以下是C#求1!+2!+3!+4!+5!的代码:
```csharp
using System;
namespace FactorialSum
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
for (int i = 1; i <= 5; i++)
{
int ret = 1;
for (int j = 1; j <= i; j++)
{
ret *= j;
}
sum += ret;
}
Console.WriteLine(sum);
}
}
}
```
输出结果为:153。
用C#计算1!+2!+3!+4!+5!
以下是用C#计算1!+2!+3!+4!+5!的代码:
```
using System;
class Program
{
static void Main(string[] args)
{
int n = 5; // 输入的n值
int ret = 1; // 阶乘的结果
int sum = 0; // 最终结果
for (int i = 1; i <= n; i++)
{
ret *= i; // 计算阶乘
sum += ret; // 将阶乘相加
}
Console.WriteLine(sum); // 输出结果
}
}
```