简体   繁体   中英

Calculate 1 + 1!/X + 2!/X^2 + … + N!/X^N

hi guys i tried to make a program in c# that calculates 1 + 1!/X + 2!/X^2 + … + N!/X^N but its giving wrong results i tried debugging it but cant find the mistake can anyone help me with that?

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);

You need to add ifac = 1; in each loop.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM