0

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);
Kys Plox
  • 774
  • 2
  • 10
  • 23

1 Answers1

6

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);
President James K. Polk
  • 40,516
  • 21
  • 95
  • 125