计算 1 + 1!/X + 2!/X^2 + … + N!/X^N
Calculate 1 + 1!/X + 2!/X^2 + … + N!/X^N
大家好,我试图用 C# 编写一个程序来计算 1 + 1!/X + 2!/X^2 + … + N!/X^N 但它给出了错误的结果我尝试调试它但不能找出错误 谁能帮我解决这个问题?
Console.WriteLine("Calculate 1 + 1!/X + 2!/X^2 + … + N!/X^N");
Console.Write("N:");
double n = double.Parse(Console.ReadLine());
Console.Write("X:");
double x = double.Parse(Console.ReadLine());
double result = 1;
int ifac = 1;
for (int i = 1; i <= n; i++)
{
for (int j = i; j >= 1; j--)
{
ifac *= j;
}
result += ifac / Math.Pow(x, i);
}
Console.WriteLine(result);
您需要在每个循环中添加ifac = 1;
。
Console.WriteLine("Calculate 1 + 1!/X + 2!/X^2 + … + N!/X^N");
Console.Write("N:");
double n = double.Parse(Console.ReadLine());
Console.Write("X:");
double x = double.Parse(Console.ReadLine());
double result = 1;
int ifac = 1;
for (int i = 1; i <= n; i++)
{
ifac = 1; //This line is very important
for (int j = i; j >= 1; j--)
{
ifac *= j;
}
result += ifac / Math.Pow(x, i);
}
Console.WriteLine(result);
大家好,我试图用 C# 编写一个程序来计算 1 + 1!/X + 2!/X^2 + … + N!/X^N 但它给出了错误的结果我尝试调试它但不能找出错误 谁能帮我解决这个问题?
Console.WriteLine("Calculate 1 + 1!/X + 2!/X^2 + … + N!/X^N");
Console.Write("N:");
double n = double.Parse(Console.ReadLine());
Console.Write("X:");
double x = double.Parse(Console.ReadLine());
double result = 1;
int ifac = 1;
for (int i = 1; i <= n; i++)
{
for (int j = i; j >= 1; j--)
{
ifac *= j;
}
result += ifac / Math.Pow(x, i);
}
Console.WriteLine(result);
您需要在每个循环中添加ifac = 1;
。
Console.WriteLine("Calculate 1 + 1!/X + 2!/X^2 + … + N!/X^N");
Console.Write("N:");
double n = double.Parse(Console.ReadLine());
Console.Write("X:");
double x = double.Parse(Console.ReadLine());
double result = 1;
int ifac = 1;
for (int i = 1; i <= n; i++)
{
ifac = 1; //This line is very important
for (int j = i; j >= 1; j--)
{
ifac *= j;
}
result += ifac / Math.Pow(x, i);
}
Console.WriteLine(result);