计算1 + 1!/ X + 2!/ X ^ 2 + ... + N!/ X ^ N.

时间:2015-03-28 10:30:51

标签: c# for-loop calculator

大家好我试着在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);

1 个答案:

答案 0 :(得分:5)

您需要在每个循环中添加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);